合并两个排序的整数数组A和B变成一个新的数组。
样例
给出A=[1,2,3,4],B=[2,4,5,6],返回 [1,2,2,3,4,4,5,6]
//简单的合并算法,时间复杂度O(max(m,n)) 空间复杂度O(m+n)
#include <stdio.h>
#include <vector>
using namespace std;
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 i=0,j=0;
int m=A.size();
int n=B.size();
vector<int> C;
while(i <= m-1 && j <= n-1){
if(A[i] <= B[j]){
C.push_back(A[i]);
i++;
}else{
C.push_back(B[j]);
j++;
}
}
while(i <= m-1){
C.push_back(A[i]);
i++;
}
while(j <= n-1){
C.push_back(B[j]);
j++;
}
return C;
}
};