描述
将按升序排序的整数数组A和B合并,新数组也需有序。
样例
样例 1:
输入:
输出:
解释:
返回合并后的数组。
样例 2:
输入:
输出:
挑战
如果一个数组很大,另一个数组很小,你将如何优化算法?
代码示例
采用归并排序策略
public class Solution {
/**
* @param A: sorted integer array A
* @param B: sorted integer array B
* @return: A new sorted integer array
*/
public int[] mergeSortedArray(int[] A, int[] B) {
int []tmp = new int[A.length+B.length];
// write your code here
int i=0;
int j=0;
int k=0;
while(i<A.length&&j<B.length){
if(A[i]<B[j]) tmp[k++]=A[i++];
else tmp[k++]=B[j++];
}
while(i<A.length)tmp[k++]=A[i++];
while(j<B.length)tmp[k++]=B[j++];
return tmp;
}
}