Two Pointers Merging sorted arrays
168. Merge Sorted Array
You are given two integer arrays, nums1 and nums2, and two integers, m and n.
The values of nums1 are its first m elements. After them, nums1 has n free places, each holding 0,
so its length is m + n. nums2 holds exactly n values. The values of each array are sorted in
non-decreasing order.
Merge the values of nums2 into nums1, so that nums1 holds all m + n values in non-decreasing order.
Change nums1 itself. The function returns nothing; the answer is what nums1 holds after it finishes.
Example 1
Input: nums1 = [2, 5, 8, 0, 0, 0]
m = 3
nums2 = [1, 5, 9]
n = 3
[1,2,5,5,8,9]Explanation: The six values in order are 1, 2, 5, 5, 8 and 9. The value 5 is in both arrays, so it appears twice.
Example 2
Input: nums1 = [-4, 0, 0, 0]
m = 2
nums2 = [-6, -1]
n = 2
[-6,-4,-1,0]Explanation: The values of nums1 are −4 and 0, and the last two zeros are free places. The 0 that is a value stays
in the answer.
Example 3
Input: nums1 = [0, 0], m = 0, nums2 = [3, 7], n = 2
[3,7]Explanation: nums1 has no values of its own, so the answer is the values of nums2.
Check your understanding
Work out the answer for this input before you write any code.
Constraints
0 ≤ m, n ≤ 1051 ≤ m + nnums1.length = m + nandnums2.length = n-109 ≤ nums1[i], nums2[i] ≤ 109- The first
melements ofnums1and all ofnums2are sorted in non-decreasing order. - The last
nelements ofnums1are 0.
Clarifying questions
What you would ask an interviewer before writing any code.