Merge Two Sorted Array II
题目:
Merge two given sorted integer array A and B into a new sorted integer array.
分析:
基本题,可做。
解法:
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
int sizeA = A.size();
int sizeB = B.size();
if (sizeA == 0) {
return B;
}
if (sizeB == 0) {
return A;
}
vector<int> res(sizeA + sizeB);
int i = 0;
int j = 0;
while (i < sizeA && j < sizeB) {
if (A[i] < B[j]) {
res[i + j] = A[i];
i++;
} else {
res[i + j] = B[j];
j++;
}
}
while (i < sizeA) {
res[i + j] = A[i];
i++;
}
while (j < sizeB) {
res[i + j] = B[j];
j++;
}
return res;
}
};