88. Merge Sorted Array

2016-09-17  本文已影响0人  a_void

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];
    }
};
上一篇下一篇

猜你喜欢

热点阅读