题目:
明显这种方法的空间耗费比较大,并且最后还进行了数组的拷贝,也是比较耗时的!换个角度思考,为什么要从头开始比较归并呢?为什么不从数组尾部开始比较归并呢?见如下代码,空间耗费更小,时间更短:
速度可媲美c++
Given two sorted integer arrays A and B, merge B into A as one sorted array.
Note:
You may assume that A has enough space (size that is greater or equal to m + n) to hold additional elements from B. The number of elements initialized in A and B are mand n respectively.
一般的归并方法:
public void merge(int A[], int m, int B[], int n) {
int C[] = new int[A.length];
int i = 0, j = 0, k = 0;
while (i < m && j < n) {
if (A[i] <= B[j]) {
C[k++] = A[i++];
} else {
C[k++] = B[j++];
}
}
while (i < m) {
C[k++] = A[i++];
}
while (j < n) {
C[k++] = B[j++];
}
System.arraycopy(C, 0, A, 0, m+n);
}
明显这种方法的空间耗费比较大,并且最后还进行了数组的拷贝,也是比较耗时的!换个角度思考,为什么要从头开始比较归并呢?为什么不从数组尾部开始比较归并呢?见如下代码,空间耗费更小,时间更短:
int i = m-1, j = n-1, k = m+n-1;
while (i >= 0 && j >= 0) {
if (A[i] >= B[j]) {
A[k--] = A[i--];
} else {
A[k--] = B[j--];
}
}
while (i >= 0) {
A[k--] = A[i--];
}
while (j >= 0) {
A[k--] = B[j--];
}
速度可媲美c++