Merge Sorted Array

Description:

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

Code:

 void merge(vector<int>& nums1, int m, vector<int>& nums2, int n) {
        vector<int> nums(nums1);
        
        int itrNums1 = 0, itrNums2 = 0;;
       
        vector<int>::iterator itr = nums.begin();
        while(itrNums1!=m && itrNums2!=n)
        {
    //如果把下面的if判断改为三目运算符会出现"runtime error"
            if (nums1[itrNums1] <= nums2[itrNums2])
            {
                *itr++ = nums1[itrNums1++];
            }
            else
            {
                *itr++ = nums2[itrNums2++];
            }
        }
        while(itrNums1!=m)
        {
            *itr++ = nums1[itrNums1++];
        }
        while(itrNums2!=n)
        {
            *itr++ = nums2[itrNums2++];
        }
        for (int i = 0 ; i < m+n; ++i)
            nums1[i] = nums[i];
    }
posted @ 2015-06-18 16:49  Rosanne  阅读(122)  评论(0编辑  收藏  举报