Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

88 合并两个有序数组 #20

Closed
sailei1 opened this issue May 17, 2019 · 0 comments
Closed

88 合并两个有序数组 #20

sailei1 opened this issue May 17, 2019 · 0 comments

Comments

@sailei1
Copy link
Owner

sailei1 commented May 17, 2019

给定两个有序整数数组 nums1 和 nums2,将 nums2 合并到 nums1 中,使得 num1 成为一个有序数组。

说明:

初始化 nums1 和 nums2 的元素数量分别为 m 和 n。
你可以假设 nums1 有足够的空间(空间大小大于或等于 m + n)来保存 nums2 中的元素。
示例:

输入:
nums1 = [1,2,3,0,0,0], m = 3
nums2 = [2,5,6], n = 3

输出: [1,2,2,3,5,6]

解法:
有序数组 越后面越大
反推对比值大小
大的 直接后面追加
小的 下标往前移动 对比 目标数组前一位
注意 最前面 数组下标 比如 -1

/**
 * @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) {
    
    for(let i=n-1;i>=0;i--){
         // console.log(nums1);
        let k=nums2[i];
        
        if(k>nums1[m-1]|| m == 0){  //最大值比较 大于 尾部追加最大值   
           nums1[m+i]=k; //   
        }else{
           // console.log(`${m+i}  ${m-1}`);
           nums1[m + i] = nums1[m - 1] //nums2不大于 num1最大值往后移动 
            m--; 
            i++; // nums2 当前值 跟 nums1 前一位 比较  m==0 防止越界
           
        }
    }
};
@sailei1 sailei1 closed this as completed May 17, 2019
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant