Merge two given sorted integer array_A_and_B_into a new sorted integer array.
How can you optimize your algorithm if one array is very large and the other is very small?
public int[] mergeSortedArray(int[] A, int[] B) {
if (A == null || B == null) {
return null;
}
int[] res = new int[A.length + B.length];
if (A.length == 0 && B.length > 0) {
return B;
} else if (A.length > 0 && B.length == 0) {
return A;
} else if (A.length == 0 && B.length == 0) {
return res;
}
int i = 0;
int j = 0;
int cur = 0;
while (i < A.length && j < B.length) {
if (A[i] < B[j]) {
res[cur] = A[i];
i++;
} else {
res[cur] = B[j];
j++;
}
cur++;
}
while (i < A.length) {
res[cur++] = A[i++];
}
while (j < B.length) {
res[cur++] = B[j++];
}
return res;
}