LintCode 6. Merge Two Sorted Arrays
Merge two given sorted ascending integer array A and B into a new sorted integer array.
题意理解
很简单的题,没有要求不能使用额外空间,就用两个指针分别从头往后比较A,B两个数组,一个个将数组组建起来。
class Solution {
public:
/**
* @param A: sorted integer array A
* @param B: sorted integer array B
* @return: A new sorted integer array
*/
vector<int> mergeSortedArray(vector<int> &A, vector<int> &B) {
int pa = 0;
int pb = 0;
vector<int> result;
while (pa < A.size() && pb < B.size()) {
if (A[pa] <= B[pb]) {
result.push_back(A[pa++]);
} else {
result.push_back(B[pb++]);
}
}
while (pa < A.size()) {
result.push_back(A[pa++]);
}
while(pb < B.size()) {
result.push_back(B[pb++]);
}
return result;
}
};