Description:
Given two sorted integer arrays nums1 and nums2, merge nums2 into nums1 as one sorted array.
Note:
You may assume that nums1 has enough space (size that is greater or equal to m + n) to hold additional elements from nums2. The number of elements initialized in nums1 and nums2 are m and n respectively.
My code:
/**
* @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, m, nums2, n) {
let cur1 = m - 1, cur2 = n - 1, curpos = m + n - 1; // cur1: nums1当前排序的元素, cur2: nums2当前排序的元素, curpos: nums1当前排序的下标
while(cur1 > -1 && cur2 > -1) {
if(nums1[cur1] > nums2[cur2]) {
nums1[curpos] = nums1[cur1];
curpos--;
cur1--;
} else {
nums1[curpos] = nums2[cur2];
curpos--;
cur2--;
}
}
while(cur2 > -1) {
nums1[curpos] = nums2[cur2];
curpos--;
cur2--;
}
};
Note:
思路不完全是自己想的,刚开始想得不对,想了很久都没想出解法,最后参考了discuss里的思路,捋了一遍。
nums1的长度为m+n,从最后往前排,即从m+n-1排最大的,到nums1[0]
网友评论