When given two sorted arrays, nums1
and nums2
, the solution should merge them into one by modifying the first array. nums1
has just enough space to store all elements from nums1
and nums2
.
Since both arrays are already sorted, you can merge two arrays by comparing the heads of each array.
If an element from the array gets filled(nums1
) is less than the other array, let that element be as is because it is already sorted.
Otherwise, you need to swap the heads of nums1
and nums2
. Then, place the head of nums2
in the correct(sorted) position so that nums2
can keep its order.
/**
* @param {number[]} nums1
* @param {number} m
* @param {number[]} nums2
* @param {number} n
* @return {void} Do not return anything, modify nums1 in-place instead.
*/
var merge = function (
nums1 = [1, 2, 3, 0, 0, 0],
m = 3,
nums2 = [2, 5, 6],
n = 3
) {
let nums1Idx = 0;
while (nums1Idx < m + n || nums2.lenth > 0) {
if (nums1Idx === m) {
// nums1 is empty, push all nums2 element into nums1
while (nums1Idx < m + n && nums2.length) {
nums1[nums1Idx] = nums2.shift();
nums1Idx++;
}
break;
}
if (nums2[0] < nums1[nums1Idx]) {
// Place the smaller element on the left side.
swap(nums1, nums2, nums1Idx, 0);
let swappedNums2Index = 0;
// If the element from nums1 is smaller than the head of nums2
// Move the new element to the right position.
while (
nums2[swappedNums2Index] > nums2[swappedNums2Index + 1] &&
swappedNums2Index < nums2.length - 1
) {
swap(nums2, nums2, swappedNums2Index, swappedNums2Index + 1);
swappedNums2Index++;
}
}
nums1Idx++;
}
};
function swap (a, b, idxA, idxB) {
const temp = a[idxA];
a[idxA] = b[idxB];
b[idxB] = temp;
};