合并有序数组

void merge(vector<int>& nums1, int m, vector<int>& nums2, int n) {
    if ((nums1.empty() && nums2.empty()) || (!nums1.empty() && nums2.empty())){
        return;
    }
    
    if (nums1.empty() && !nums2.empty()){
        nums1 = nums2;
        return;
    }
    
    vector<int> mergedNums;
    
    auto it1  = nums1.cbegin();
    auto it2  = nums2.cbegin();
    auto end1 = nums1.cbegin() + m;
    auto end2 = nums2.cbegin() + n;
    
    while (it1 != end1 || it2 != end2){
        
        if (it1 == end1 && it2 != end2) {
            mergedNums.push_back(*it2);
            ++it2;
        }
        else if (it1 != end1 && it2 == end2){
            mergedNums.push_back(*it1);
            ++it1;
        }
        else if (*it1 < *it2){
            mergedNums.push_back(*it1);
            ++it1;
        }
        else{
            mergedNums.push_back(*it2);
            ++it2;
        }
    }
    
    nums1 = mergedNums;
}

 

posted @ 2015-08-12 18:02  wu_overflow  阅读(157)  评论(0编辑  收藏  举报