美文网首页
88. Merge Sorted Array

88. Merge Sorted Array

作者: a_void | 来源:发表于2016-09-17 11:47 被阅读0次

    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];
        }
    };
    

    相关文章

      网友评论

          本文标题:88. Merge Sorted Array

          本文链接:https://www.haomeiwen.com/subject/jaaiettx.html