You are given two integer arrays
Merge
The final sorted array should not be returned by the function, but instead be stored inside the array
Output: [1,2,2,3,5,6]
Explanation: The arrays we are merging are [1,2,3] and [2,5,6].
The result of the merge is [1,2,2,3,5,6] with the underlined elements coming from nums1.
Output: [1]
Explanation: The arrays we are merging are [1] and [].
The result of the merge is [1].
Output: [1]
Explanation: The arrays we are merging are [] and [1]. The result of the merge is [1].
Note that because m = 0, there are no elements in nums1. The 0 is only there to ensure the merge result can fit in nums1.
Constraints:
nums1.length == m + n nums2.length == n 0 <= m, n <= 200 1 <= m + n <= 200 -109 <= nums1[i], nums2[j] <= 109
Follow up: Can you come up with an algorithm that runs in
Contents
Solution 1 - Start filling nums1 array from right side with higher elements
As per the problem statement, input arrays
Now, we have to fill elements from
So, in this approach, we will starting filling
Implementation steps:
-
As a first step, We will create a variable
last and initialize with last index ofnums1 array,last = nums1.length -1; . We will also utilize inputsm andn as two pointers to point tonums1 andnums2 respectively. -
Then, while
m > 0 andn > 0 , we will check the elements fromnums1 andnums2 and copy the highest element tonums1 from right side. If we copy element fromnums1 , decrementm , or if we copy element fromnums2 , decrementn . -
At the end, we may still have some elements in
nums2 , just like above examplenums1 = [4, 5, 6, 0, 0, 0] andnums2 = [1, 2, 3] , sincenums1 have highest elements, we will copy all elements fromnums1 , and when we exit thewhile loop, we will have elements left innums2 , so we will simply copy all remaining elements fromnums2 .
Complexity Analysis:
Time complexity: Above code runs in O(m + n) time where
Space complexity: O(1).
Above implementations source code can be found at