合并两个排序的整数数组A和B变成一个新的数组。
Merge two given sorted integer array A and B into a new sorted integer array.
样例
给出A=[1,2,3,4],B=[2,4,5,6],返回 [1,2,2,3,4,4,5,6]
挑战
你能否优化你的算法,如果其中一个数组很大而另一个数组很小?
How can you optimize your algorithm if one array is very large and the other is very small?
class Solution {
/**
* @param A and B: sorted integer array A and B.
* @return: A new sorted integer array
*/
public ArrayList<Integer> mergeSortedArray(ArrayList<Integer> A, ArrayList<Integer> B) {
if(A.size() > B.size()) {//长度 A.size() <= B.size()
ArrayList<Integer> temp = A;
A = B;
B = temp;
}
int i = 0, j = 0;
while(i < A.size() && j < B.size()) {//将A内元素插到B合适位置上
if(A.get(i) <= B.get(j)) {
B.add(j, A.get(i));
j++;***//其实,可以通过二分查找的方法确定j值(当B数据很大时。)***
i++;
} else {
j++;
}
}
if(j == B.size() && i < A.size()) {//B移动到了末尾,将A剩余元素插到B尾部。
while(i < A.size()) {
B.add(A.get(i));
i++;
}
}
return B;
}
}