合并两个排序的整数数组A和B变成一个新的数组。给出A=[1,2,3,4],B=[2,4,5,6],返回 [1,2,2,3,4,4,5,6]
#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <string>
#include <cstring>
#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) {
vector<int> C;
C.clear();
int sizeA = A.size();
int sizeB = B.size();
int indexA = 0, indexB = 0;
while(indexA < sizeA && indexB < sizeB) {
if(A[indexA] < B[indexB]) {
C.push_back(A[indexA]);
indexA++;
}else if(A[indexA] > B[indexB]) {
C.push_back(B[indexB]);
indexB++;
} else if(A[indexA] == B[indexB]){
C.push_back(A[indexA]) ;
C.push_back(B[indexB]);
indexA++;
indexB++;
}
}
if(indexA == sizeA) {
while(indexB < sizeB) {
C.push_back(B[indexB]);
indexB++;
}
} else if(indexB == sizeB) {
while(indexA < sizeA) {
C.push_back(A[indexA]);
indexA++;
}
}
return C;
}
};
int main() {
vector<int> A;
vector<int> B;
int n, m;
while(scanf("%d%d", &n, &m) != EOF) {
int read;
A.clear();
B.clear();
for(int i = 0; i < n; i++) {
scanf("%d", &read);
A.push_back(read);
}
for(int i = 0; i < m; i++) {
scanf("%d", &read);
B.push_back(read);
}
Solution *obj = new Solution();
vector<int> result = obj->mergeSortedArray(A, B);
int vectorSize = (int)result.size();
for(int i = 0; i < vectorSize; i++) {
printf("%d ", result[i]);
}
cout << endl;
}
return 0;
}