Merge two given sorted integer array A and B into a new sorted integer array.
Example
A=[1,2,3,4]
B=[2,4,5,6]
return [1,2,2,3,4,4,5,6]
Challenge
Solution:
How can you optimize your algorithm if one array is very large and the other is very small?
public ArrayList<Integer> mergeSortedArray(ArrayList<Integer> A, ArrayList<Integer> B) {
ArrayList<Integer> result = new ArrayList<Integer>();
if (A == null || A.size() == 0) {
return (new ArrayList<Integer>(B));
} else if (B == null || B.size() == 0) {
return (new ArrayList<Integer>(A));
}
int aIndex = 0;
int bIndex = 0;
int a;
int b;
if (A.size() > B.size()) {
int index = bs(A, B.get(0));
while (aIndex < index) {
result.add(A.get(aIndex++));
}
} else {
int index = bs(B, A.get(0));
while (bIndex < index) {
result.add(B.get(bIndex++));
}
}
while (aIndex < A.size() && bIndex < B.size()) {
a = A.get(aIndex);
b = B.get(bIndex);
if (a < b) {
result.add(a);
aIndex++;
} else {
result.add(b);
bIndex++;
}
}
while (aIndex < A.size()) {
result.add(A.get(aIndex++));
}
while (bIndex < B.size()) {
result.add(B.get(bIndex++));
}
return result;
}
private int bs(ArrayList<Integer> A, int target) {
int start = 0;
int end = A.size() - 1;
int mid;
while (start + 1 < end) {
mid = start + ((end - start) >> 1);
if (A.get(mid) == target) {
return mid;
} else if (A.get(mid) > target) {
end = mid;
} else {
start = mid;
}
}
if (A.get(end) <= target) {
return end;
}
if (A.get(start) <= target) {
return start;
}
return 0;
}
思路:
1. 依次比较,剩下的全部加进去
2. 长短list。使用二分搜索,在长list里找到短list中的最小值。返回和最小值相等或者小于最小值的index。将长list在index之前的全部加入到result中,剩下的一次比较。
Note:
ArrayList与vector都是以数组形式存储,LinkedList是链表形式存储。