Given two sorted integer arrays nums1 and nums2 , merge nums2 into nums1 as one sorted array.
Note:
The number of elements initialized in nums1 and nums2 are m and n respectively.
You may assume that nums1 has enough space (size that is greater or equal to m + n ) to hold additional elements from nums2.
Example:
Input:
nums1 = [1,2,3,0,0,0], m = 3
nums2 = [2,5,6], n = 3
Output: [1,2,2,3,5,6]
/**
* @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) {
var right = n - 1;
var left = m - 1;
var i = nums1.length - 1;
while (right >= 0 && left >= 0) {
if (nums2[right] > nums1[left]) {
nums1[i] = nums2[right];
right--;
} else {
nums1[i] = nums1[left];
left--;
}
i--;
}
while(right >=0) {
nums1[i] = nums2[right];
right--;
i--;
}
};
混合插入有序數(shù)組,由于兩個(gè)數(shù)組都是有序的,所有只需要按順序比較大小,然后nums1的數(shù)組是足夠大的,所以從nums1和nums2的數(shù)組末尾一個(gè)一個(gè)進(jìn)行比較畏妖,把較大的數(shù)按順序加入混合之后的末尾。需要三個(gè)變量left,right,和i,分別只想nums1姥芥、nums2和混合數(shù)組的末尾。進(jìn)行while循環(huán)汇鞭。如果left和right都大于等于0凉唐,那么再看nums1[left]和nums2[right],如果nums1[left] > nums2[right],則把nums1[left]插入混合數(shù)組的末尾霍骄,然后i--台囱,left--;反之就把nums[right]加入混合數(shù)組的末尾读整,然后right和i都--簿训;循環(huán)結(jié)束后,有可能left或者right還大于等于0米间;若right還大于等于0强品,那還要接著循環(huán),將nums2中的數(shù)字繼續(xù)考入nums1屈糊;若left大于等于0那就不用管的榛,因?yàn)榛旌蠑?shù)組本身就存在nums1中。
更為簡(jiǎn)潔的代碼如下
var merge = function(nums1, m, nums2, n) {
var left = m - 1;
var right = n - 1;
var k = m + n - 1;
while(right >= 0) {
nums1[k--] = (left >=0 && nums2[right] < nums1[left]) ? nums1[left--] : nums2[right--]
}
}