leetCode打卡——88 merge sorted array

300 阅读1分钟

题目

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.

思路

  1. 结果数组足够大,只在结果数组原地排序,那么从后面排序就ok;
  2. 比较两个数组当前的尾部数字,较大的一个放在结果数组的当前指定位置,指定位置减1
var merge = function(nums1, m, nums2, n) {
    const len = m + n;
    let a1Index = m - 1;
    let a2Index = n - 1;
    for (let i = len - 1; i >= 0; i--) {
        const val1 = typeof nums1[a1Index] !== 'number' ? -Infinity : nums1[a1Index] ;
        const val2 = typeof nums2[a2Index] !== 'number' ? -Infinity : nums2[a2Index] ;

        const nowVal = Math.max(val1, val2);
        
        nums1[i] = nowVal;

        if (val1 > val2) {
            a1Index--;
        } else {
            a2Index--;
        }
    }
};