Merge Sorted Array leetcode

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 nums1and nums2 are m and n respectively.

 

Subscribe to see which companies asked this question

void merge(vector<int>& nums1, int m, vector<int>& nums2, int n) {
        int len = m + n;
        vector<int>::iterator iter1 = nums1.begin();
        vector<int>::iterator iter2 = nums2.begin();
        while (iter1 != nums1.begin() + m && iter2 != nums2.begin() + n)
        {
            if (*iter2 > *iter1)
                iter1++;
            else
            {
                iter1 = nums1.insert(iter1, 1, *iter2);
                iter1++;
                m++;
                iter2++;
            }
        }
        if (iter2 != nums2.begin() + n)
            nums1.insert(iter1, iter2, nums2.end());
        nums1.resize(len);
    }

 

posted @ 2016-01-03 22:28  sdlwlxf  阅读(164)  评论(0编辑  收藏  举报