[CareerCup] 11.1 Merge Arrays 合併陣列

Grandyang發表於2015-10-14

 

11.1 You are given two sorted arrays, A and B, where A has a large enough buffer at the end to hold B. Write a method to merge B into A in sorted orde.

 

LeetCode上的原題,請參見我之前的部落格Merge Sorted Array 混合插入有序陣列

 

class Solution {
public:
    void merge(vector<int> &a, int m, vector<int> &b, int n) {
        int cnt = m + n - 1;
        --m; --n;
        while (m >= 0 && n >= 0) a[cnt--] = a[m] > b[n] ? a[m--] : b[n--];
        while (n >= 0) a[cnt--] = b[n--];
    }
};

 

相關文章