You have two lists of numbers that are each already sorted from smallest to largest, and you want to combine them into one sorted list without allocating a new array.
The first array, nums1, has room for both lists: its first m slots hold real values and its last n slots are placeholders filled with 0. The second array, nums2, holds n values. Rearrange nums1 in place so that it contains all m + n values in sorted order. Nothing needs to be returned.
Example:
Input: nums1 = [1, 4, 7, 0, 0], m = 3, nums2 = [2, 8], n = 2 Result: nums1 becomes [1, 2, 4, 7, 8]
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