合并两个排序的整数数组A和B变成一个新的数组。
样例
给出A=[1,2,3,4],B=[2,4,5,6],返回 [1,2,2,3,4,4,5,6]
之前想的是用剑指offer里替换空格那种方法 但是把问题复杂化了 直接对比A.B 然后压到C里就行。
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> C;
int a = 0, b = 0;
while (a < (int)A.size() && b < (int)B.size())
{
if (A[a] <= B[b])
C.push_back(A[a++]);
else
C.push_back(B[b++]);
}
while (a < (int)A.size())
C.push_back(A[a++]);
while (b < (int)B.size())
C.push_back(B[b++]);
return C;
}
};