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.
A common mistake is to start merging from the beginning of nums1. This would require shifting elements and would be inefficient. The optimal approach is to start merging from the end of the arrays.
- Initialize three pointers:
p1pointing to the last valid element ofnums1(at indexm-1),p2pointing to the last element ofnums2(at indexn-1), andppointing to the very end of thenums1array (at indexm+n-1). - Use a while loop that continues as long as
p2is non-negative (meaning there are still elements innums2to merge). - Inside the loop, compare the elements at
nums1[p1]andnums2[p2].- If
p1is valid (>= 0) andnums1[p1]is greater thannums2[p2], placenums1[p1]at indexpand decrementp1. - Otherwise, place
nums2[p2]at indexpand decrementp2.
- If
- Decrement the main pointer
pin each iteration.
This approach works because we are filling nums1 from the back, so we never overwrite an element in nums1 that we still need to compare. The time complexity is O(m+n) and the space complexity is O(1).
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16