合并两个排序的整数数组A和B变成一个新的数组。
样例
给出A=[1,2,3,4],B=[2,4,5,6],返回 [1,2,2,3,4,4,5,6]
挑战
你能否优化你的算法,如果其中一个数组很大而另一个数组很小?
class Solution {
/**
* @param A and B: sorted integer array A and B.
* @return: A new sorted integer array
*/
public int[] mergeSortedArray(int[] A, int[] B) {
// Write your code here
if(A.length==0)
return B;
if(B.length==0)
return A;
int []C=new int[A.length+B.length];
int i=0;//A
int j=0;//B
int k=0;//C
while(i<A.length&&j<B.length){
if(A[i]>B[j]){
C[k++]=B[j++];
}else{
C[k++]=A[i++];
}
}
while(i<A.length){
C[k++]=A[i++];
}
while(j<B.length){
C[k++]=B[j++];
}
return C;
}
}