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

10、合并两个有序数组 #10

Open
conan1992 opened this issue Mar 25, 2020 · 0 comments
Open

10、合并两个有序数组 #10

conan1992 opened this issue Mar 25, 2020 · 0 comments
Labels

Comments

@conan1992
Copy link
Owner

题目描述

给你两个有序整数数组 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]

分析

因为合并后的有效长度是m+n,且nums1有足够的空间,所以采用从后面开始填充数据;循环的终止条件是nums2的各项都添加到nums1了,但是要考虑到m为0的时候得情况

/**
 * @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 sum = m + n - 1;
    while(n>0){
        if(m==0){
            nums1[sum] = nums2[n-1]
            sum--;
            n--
        }else if(nums1[m-1]>nums2[n-1]){
            nums1[sum] = nums1[m-1]
            sum--;
            m--
        }else{
            nums1[sum] = nums2[n-1]
            sum--;
            n--
        }
    }
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

1 participant