88 Merge Sorted Array
Problem Statement
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.
Instructions
Merge
nums1
andnums2
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 ofm + n
, where the firstm
elements denote the elements that should be merged, and the lastn
elements are set to0
and should be ignored.nums2
has a length ofn
.
For the whole problem statement, please refer here.
Plans
Use three pointers to compare the elements from the end of both arrays and place the larget element at the end of
nums1
.Since
nums1
has enough space to accomodate all elements from both arrays, we can start merging from the end ofnums1
to avoid overwriting elements that have not been processed yet.After one of the arrays is fully processed, copy any remaining elements from the other array into
nums1
.
Solution
Explanation
Initialization
We initialize the three pointers
p1
for the last valid elements innums1
,p2
for the last elements innums2
, andp
for the last position in the merged arraynums1
.
Merging from the End
We use
while
loop to compare the elements from the end of the both arrays (nums1
andnums2
). The loop continues as long as there are elements left in both arrays (p1 >= 0
andp2 >= 0
).Inside the loop, we compare the elements at
nums1[p1]
andnums2[p2]
. The larger element is placed at thenums1[p]
, and the corresponding pointer (p1
orp2
) is decremented.
Handling the Remaining Elements
After the main loop, if there are any remaining elements in
nums2
(i.e.,p2 >= 0
), we copy them to the beginning ofnums1
. This is because all the elements isnums1
have already been processed and moved to their correct positions.We use another
while
loop to copy the remainng elements fromnums2
tonums1
. The loop continues as long as there are elements left innums2
(p2 >= 0
).
Last updated