Merge Two Sorted Array
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) {
if (A == null || A.length == 0) return B;
if (B == null || B.length == 0) return A;
int[] result = new int[A.length + B.length];
int left = 0;
int right = 0;
int cur = 0;
while (left < A.length && right < B.length) {
if (A[left] < B[right]) {
result[cur++] = A[left++];
} else {
result[cur++] = B[right++];
}
}
while (left < A.length) result[cur++] = A[left++];
while (right < B.length) result[cur++] = B[right++];
return result;
}
}
最后更新于
这有帮助吗?