[leetcode]88. Merge Sorted Array

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 nrespectively.
  • 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]

分析:

合并两个有序数组,可以假设nums1数组有足够的空间,即大小为m+n,所以从最后面开始往前赋值,先比较数组1和数组2中最后一个元素的大小,把较大的那个插入到m+n-1的位置上,再依次向前推。如果1中所有的元素都比2小,那么前m个还是1原来的内容,没有改变。如果1中的数组比2大的,当1循环完了,2中还有元素没加入1,直接用个循环把2中所有的元素覆盖到1剩下的位置。

class Solution {
public:
    void merge(vector<int>& nums1, int m, vector<int>& nums2, int n) {
        int len = m+n-1;
        m--;
        n--;
        while(m>=0 && n>=0)
        {
            if(nums1[m] <= nums2[n])
                nums1[len--] = nums2[n--];
            else
                nums1[len--] = nums1[m--];
        }
        while(n>=0)
            nums1[len--] = nums2[n--];
    }
    
};

猜你喜欢

转载自blog.csdn.net/weixin_41814716/article/details/84099299