Merge Sorted Arrays
Given two sorted integer arrays, nums1 and nums2, and the number of data elements in each array, m and n, implement a function that merges the second array into the first one. You have to modify nums1 in place.
Merge Sorted Array
Problem Statement
You are given two sorted integer arrays, nums1 and nums2. You are also given m and n, which tell you how many actual data elements are in each array.
Your task is to merge nums2 into nums1, so that nums1 becomes one single sorted array. You must change nums1 in place (without creating a new array).
Note: Assume
nums1has a size equal tom + n. This means it already has enough empty space at the end to hold all the elements fromnums2.
Constraints
nums1.length = m + nnums2.length = n0 ≤ m, n ≤ 2001 ≤ m + n ≤ 200−10³ ≤ nums1[i], nums2[j] ≤ 10³
Examples
Example 1
Input:
nums1 = [3, 4, 9, 0, 0, 0], m = 3nums2 = [1, 2, 7], n = 3
Output: [1, 2, 3, 4, 7, 9]
Example 2
Input:
nums1 = [1, 4, 9, 0, 0], m = 3nums2 = [1, 7, 6], n = 2
Output: [1, 1, 4, 9, 7, 6]
Solution
We start comparing from the end of both arrays, not the beginning. This lets us fill in nums1 from the back, without overwriting any values we still need.
Steps
- We set up two pointers:
p1, starting at the last real data element innums1(indexm - 1).p2, starting at the last element innums2(indexn - 1).
- We also use a third pointer,
p, starting at the very last index ofnums1(indexm + n - 1). This is where we'll place the next value. - We compare
nums1[p1]andnums2[p2]:- Whichever value is larger, we place it at position
pinnums1. Then we move that pointer (p1orp2) one step back. - We always move
pone step back after placing a value.
- Whichever value is larger, we place it at position
- We keep doing this until we've placed all the remaining elements from
nums2. Sincenums1is being filled from the back, we don't need to worry aboutnums1's own remaining elements — they're already in the correct sorted spot.
Code
function mergeSorted(nums1, m, nums2, n) {
let p1 = m - 1;
let p2 = n - 1;
for (let p = n + m - 1; p > -1; p--) {
if (p2 < 0) {
break;
}
if (p1 >= 0 && nums1[p1] > nums2[p2]) {
nums1[p] = nums1[p1];
p1 -= 1;
} else {
nums1[p] = nums2[p2];
p2 -= 1;
}
}
return nums1;
}