















- 2 mins
Given two sorted integer arrays nums1 and nums2, merge nums2 into nums1 as one sorted array.
Note:
Example:
Input:
nums1 = [1,2,3,0,0,0], m = 3
nums2 = [2,5,6], n = 3
Output: [1,2,2,3,5,6]
const merge = function (nums1, m, nums2, n) {
let first = m - 1;
let second = n - 1;
for (let i = m + n - 1; i >= 0; i--) {
if (second < 0) {
break;
}
if (nums1[first] > nums2[second]) {
nums1[i] = nums1[first];
first--;
} else {
nums1[i] = nums2[second];
second--;
}
}
};
Approach:
Start from back of nums1 and iterate through both lists backwards, putting the larger of nums1[m] and nums2[n] into the last element of nums1 so far. Starting from the back allows us to do this in one loop.
Once an element is copied over, it is in it’s “final spot” in the sorted array, and will not move again.
The algorithm has a runtime of O(m+n) and space of O(1).
The latter is true because even though a variable is initialized, it is not a function of the inputs m or n.
Note: This could have been done without initializing ‘final’ at all, but it reads better with it.
const merge = function (nums1, m, nums2, n) {
let final = m + n - 1;
m--;
n--;
while (m >= 0 || n >= 0) {
// if no more nums2 then just copy remaining m elements
if (n < 0 || nums1[m] > nums2[n]) {
nums1[final] = nums1[m];
m--;
} else { // m < 0 || nums1[m] < nums2[n]
nums1[final] = nums2[n];
n--;
}
final--;
}
return nums1;
};
此内容由惯性聚合(RSS阅读器)自动聚合整理,仅供阅读参考。 原文来自 — 版权归原作者所有。