描述
合併兩個排序的整數數組A和B變成一個新的數組。
樣例
給出A=[1,2,3,4],B=[2,4,5,6],返回 [1,2,2,3,4,4,5,6]
解決方案
歸併排序中使用到了排序數組的合併,所以該問題的解決方案已經很成熟,本文參照《Algorithm 4th Edition》中歸併排序一節裏的代碼給出實現:
class Solution {
public:
/**
* @param A and B: sorted integer array A and B.
* @return: A new sorted integer array
*/
vector<int> mergeSortedArray(vector<int> &A, vector<int> &B) {
// write your code here
vector<int> res(A.size() + B.size());
auto itA = A.cbegin();
auto itB = B.cbegin();
for(auto itR = res.begin(); itR != res.end(); ++itR) {
if(itA == A.cend()) *itR = *(itB++);
else if(itB == B.cend()) *itR = *(itA++);
else if(*itB < *itA) *itR = *(itB++);
else *itR = *(itA++);
}
return res;
}
};