Logo
1

Leetcode help

You are given two integer arrays nums1 and nums2, sorted in non-decreasing order, and two integers m and n, representing the number of elements in nums1 and nums2 respectively.

Merge nums1 and nums2 into a single array sorted in non-decreasing order.

The final sorted array should not be returned by the function, but instead be stored inside the array nums1. To accommodate this, nums1 has a length of m + n, where the first m elements denote the elements that should be merged, and the last n elements are set to 0 and should be ignored. nums2 has a length of n.

davidmacagodavidmacago asked a year ago

·

Answers

1

Array length is determined by counting items from 1, 2 and so on.
If we need to find the items of array we need to use positions starting from 0.

For example:

array = ["orange", "apple", "pear"]
array[1] // apple
array.length // 3

sum of m and n gives the total length of required array. n gives the length of array to be replaced.

under while loop position_to_be_replaced is checked whether it is greater than 0 or not, if yes we add the new values from nums2 to the nums1.

After we add all the required value, sort method is used to arrangle them in ascending order.

var merge = function(nums1, m, nums2, n) {
    nums1_position = m + n - 1
    position_to_be_replaced = n - 1

    while(position_to_be_replaced >= 0) {
        nums1[nums1_position] = nums2[position_to_be_replaced]
        nums1_position--
        position_to_be_replaced--
    }
 
    nums1.sort((a,b) => a-b)
};

davidmacagodavidmacago edited a year ago

Post your answer

Recommended Books

Reading books is a great way to learn. Here are some of the books we recommend.