好复杂的二分思路。。。。
public static double findMedianSortedArrays(int[] A, int[] B) {
if (A == null && B == null)
return -1;
// if (A == null || A.length == 0) //不可,另一个 可能是偶数个
// return B[B.length / 2];
// if (B == null || B.length == 0)
// return A[A.length / 2];
int count = A.length + B.length;
if ((count & 1) == 1)
return getK(A, 0, A.length - 1, B, 0, B.length - 1, count / 2 + 1);
else {
double sum = getK(A, 0, A.length - 1, B, 0, B.length - 1,
count / 2 + 1)
+ getK(A, 0, A.length - 1, B, 0, B.length - 1, count / 2);
return sum / 2;
}
}
//这个函数的作用是找到两个数组中的第k个数
public static int getK(int A[], int aBeg, int aEnd, int B[], int bBeg,
int bEnd, int k) {
System.out.println(aBeg+" "+aEnd+" "+bBeg+" "+bEnd+" "+k);
if(aBeg>aEnd){ //A已经不用考虑了,直接在B中就可以求出第K个数
return B[bBeg+k-1];
}
if(bBeg>bEnd){
return A[aBeg+k-1];
}
//k==1的时候,表示当前所有数据里面,最小的那个数据 就是第k个值啦,所以以下:
if(k==1) return Math.min(A[aBeg], B[bBeg]);
int aMid = (aBeg + aEnd) / 2;
int bMid = (bBeg + bEnd) / 2;
int count = aMid - aBeg + bMid - bBeg + 2;
// if (count == k) // 注意k==count时 不代表 最大值就是那个k值 例子 {1 2 }{1 1}
// return Math.max(A[aMid], B[bMid]);
if (count > k) {
if (A[aMid] > B[bMid]) {
return getK(A, aBeg, aMid-1 , B, bBeg, bEnd, k); // 忘记return了。。
} else {
return getK(A, aBeg, aEnd, B, bBeg, bMid-1 , k);
}
} else {
if (A[aMid] < B[bMid]) {
return getK(A, aMid+1 , aEnd, B, bBeg, bEnd, k - (aMid-aBeg+1) ); //这里的+1不可以省略,否则会死循环!!!
} else {
return getK(A, aBeg, aEnd, B, bMid+1 , bEnd, k - (bMid-bBeg+1) );
}
}
}