Merge Sorted Arrays
EasyTwo Pointers · Oracle
You are given two integer arrays sorted in non-decreasing order:
nums1, of lengthm + n. Its firstmentries are the real values; the lastnentries are0placeholders that only reserve space.nums2, of lengthn.
Merge nums2 into nums1 in place so that nums1 holds all m + n values in non-decreasing order. Keep duplicates. Do not return anything; the grader checks the contents of nums1 after your function finishes.
Example 1
- Input:
- nums1 = [2,5,9,0,0,0], m = 3, nums2 = [1,5,7], n = 3
- Output:
- [1,2,5,5,7,9]
- Explanation
- Only the first 3 entries of
nums1are real ([2,5,9]); the zeros are spare room. After merging,nums1holds all six values in order, including both 5s.
Example 2
- Input:
- nums1 = [4,6,0,0], m = 2, nums2 = [8,10], n = 2
- Output:
- [4,6,8,10]
- Explanation
- Every value in
nums2is larger than the values innums1, so they simply fill the two spare slots.
Example 3
- Input:
- nums1 = [0,0], m = 0, nums2 = [-3,4], n = 2
- Output:
- [-3,4]
- Explanation
m = 0, sonums1holds no real values yet. Both zeros are placeholders and are overwritten bynums2.
Constraints
nums1.length == m + n,nums2.length == n0 <= m, n <= 200,1 <= m + n <= 200-10^9 <= nums1[i], nums2[j] <= 10^9- The first
mvalues ofnums1and all ofnums2are sorted in non-decreasing order