88. Merge Sorted Array

Given two sorted integer arrays nums1 and nums2, merge nums2 into nums1 as one sorted array.

Note:You may assume that nums1 has enough space (size that is greater or equal to m + n) to hold additional elements from nums2. The number of elements initialized in nums1 and nums2 are m and n respectively.

class Solution {
public:
    void merge(vector<int>& nums1, int m, vector<int>& nums2, int n) {
        vector<int> t = vector<int>(nums1);
        nums1.resize(m+n);
        int p1 = 0, p2 = 0;
        while(p1 < m && p2 < n){
            if(t[p1] < nums2[p2]){
                nums1[p1+p2] = t[p1++];
            }else{
                nums1[p1+p2] = nums2[p2++];
            }
        }
        for(int i=p1;i<m;i++) nums1[i+n] = t[i];
        for(int i=p2;i<n;i++) nums1[i+m] = nums2[i];
    }
};

推荐阅读更多精彩内容