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.
p1
pointing to the last valid element of nums1
(at index m-1
), p2
pointing to the last element of nums2
(at index n-1
), and p
pointing to the very end of the nums1
array (at index m+n-1
).p2
is non-negative (meaning there are still elements in nums2
to merge).nums1[p1]
and nums2[p2]
.
p1
is valid (>= 0) and nums1[p1]
is greater than nums2[p2]
, place nums1[p1]
at index p
and decrement p1
.nums2[p2]
at index p
and decrement p2
.p
in 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