Merge Sorted Array (88)
Given two sorted integer arrays nums1 and nums2, merge nums2 into nums1 as one sorted array.
Note:
The number of elements initialized in nums1 and nums2 are m and n respectively.
You may assume that nums1 has enough space (size that is equal to m + n) to hold additional elements from nums2.
Approach:
We cannot iterate thorugh both array on tandem as if an entry in the second array is smaller than some entry in the first array, we would have to shift all the subsequent entries in the first array by 1, potentially rendering the worst came time to O(mn)
if every entry in array2 is smaller than each entry in array1.
Since we have spare space at the end of the first array. We take advantage of this by filling the first array from its end. The last element in the result will be written to index m + n - 1
. nums1 would be updated in the follwing manner
Time: O(m + n) Space: O(1)
Last updated
Was this helpful?