Given two sorted integer arrays nums1 and nums2 in non-decreasing order, with lengths m and n respectively, merge them into nums1 while maintaining sorted order.
Implementation Code
function merge(nums1, m, nums2, n) {
let i = nums1.length - 1;
m--;
n--;
while(n >= 0) {
while(m >= 0 && nums1[m] > nums2[n]) {
[nums1[m], nums1[i]] = [nums1[i], nums1[m]];
m--;
i--;
}
nums1[i--] = nums2[n--];
}
}
Key Learning Points
-
Array Element Swapping in JavaScript Using ES6 destructuring assignment for concise element swapping:
[nums1[m], nums1[i]] = [nums1[i], nums1[m]]; -
Array Length Syntax
nums1.length -
Alternative Solution
function merge(nums1, m, nums2, n) { nums1.splice(m, nums1.length - m, ...nums2); nums1.sort((a, b) => a - b); }This approach:
- Uses
splicetoo replace elements innums1starting from indexmwith elements fromnums2 - Applies
sortwith a comparison function for ascending order
- Uses
-
Two-Pointer Technique
function merge(nums1, m, nums2, n) { let p1 = 0, p2 = 0; const sorted = new Array(m + n).fill(0); let current; while(p1 < m || p2 < n) { if(p1 === m) { current = nums2[p2++]; } else if(p2 === n) { current = nums1[p1++]; } else if(nums1[p1] < nums2[p2]) { current = nums1[p1++]; } else { current = nums2[p2++]; } sorted[p1 + p2 - 1] = current; } for(let i = 0; i < m + n; i++) { nums1[i] = sorted[i]; } }This method uses two pointers to efficiently merge the arrays by comparing elements at each positoin.