描述
合并两个排序的整数数组A和B变成一个新的数组。
你可以假设A具有足够的空间(A数组的大小大于或等于m+n)去添加B中的元素。
您在真实的面试中是否遇到过这个题?
是
样例
给出 A = [1, 2, 3, empty, empty]
, B = [4, 5]
合并之后 A 将变成 [1,2,3,4,5]
采用了与合并数组II同样的方法
class Solution {
public:
/*
* @param A: sorted integer array A which has m elements, but size of A is m+n
* @param m: An integer
* @param B: sorted integer array B which has n elements
* @param n: An integer
* @return: nothing
*/
void mergeSortedArray(int A[], int m, int B[], int n) {
// write your code here
int C[m];
for(int i=0;i<m;i++) C[i]=A[i];
int a=0;
int b=0;
while(a<m&&b<n){
if(C[a]>B[b]){
A[a+b]=B[b];
b++;
}else{
A[a+b]=C[a];
a++;
}
}
if(a!=m){
while(a<m){
A[a+b]=C[a];
a++;
}
}
if(b!=n){
while(b<n){
A[a+b]=B[b];
b++;
}
}
}
};