leetcode 88. C ++ merge two ordered arrays

Leetcode 88. merge two ordered arrays

Given two ordered arrays of integers and nums2 nums1, incorporated into the nums2 nums1 in an ordered array such as a num1.

Description:

And initializing the number of elements nums1 nums2 of m and n.
You can assume nums1 sufficient space (space equal to or greater than m + n) to save the elements of 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]

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

 

Guess you like

Origin www.cnblogs.com/xiaotongtt/p/11305770.html