Skip to content

Instantly share code, notes, and snippets.

@ykdojo
Created March 25, 2019 17:34
Show Gist options
  • Save ykdojo/778a51a2c75caf57d1bc59cf3ede1c32 to your computer and use it in GitHub Desktop.
Save ykdojo/778a51a2c75caf57d1bc59cf3ede1c32 to your computer and use it in GitHub Desktop.
/**
* @param {number[]} nums1
* @param {number} m
* @param {number[]} nums2
* @param {number} n
* @return {void} Do not return anything, modify nums1 in-place instead.
*/
// NOTE: extra space: O(m), time: O(n + m)
var merge = function(nums1, m, nums2, n) {
nums1Copy = Array(m);
for (let i = 0; i < m; i++) {
nums1Copy[i] = nums1[i];
}
let i1 = 0;
let i2 = 0;
while (i1 < m || i2 < n) {
if (i1 >= m) {
nums1[i1 + i2] = nums2[i2];
i2 += 1;
}
else if (i2 >= n) {
nums1[i1 + i2] = nums1Copy[i1];
i1 += 1;
}
else if (nums1Copy[i1] <= nums2[i2]) {
nums1[i1 + i2] = nums1Copy[i1];
i1 += 1;
} else {
nums1[i1 + i2] = nums2[i2];
i2 += 1;
}
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment