AFFILIATE LINKS
Great resource I use to learn algorithms.
40% off Tech Interview Pro: http://techinterviewpro.com/terriblewhiteboard
20% off CoderPro: http://coderpro.com/terriblewhiteboard
Here is the full implementation.
/**
* @param {number[]} nums1
* @param {number} m
* @param {number[]} nums2
* @param {number} n
* @return {void} Do not return anything, modify nums1 in-place instead.
*/
let merge = function(nums1, m, nums2, n) {
let first = m - 1;
let second = n - 1;
for (var i = m + n - 1; i >= 0; i--) {
if (second < 0) {
break;
}
if (first >= 0 && nums1[first] > nums2[second]) {
nums1[i] = nums1[first];
first--;
} else {
nums1[i] = nums2[second];
second--;
}
}
};
Java Solution
class Solution {
public void merge(int[] nums1, int m, int[] nums2, int n) {
int first = m - 1;
int second = n - 1;
for (int i = nums1.length - 1; i >= 0; i--) {
if (second < 0) {
return;
}
if (first >= 0 && nums1[first] > nums2[second]) {
nums1[i] = nums1[first];
first--;
} else {
nums1[i] = nums2[second];
second--;
}
}
}
}