两个排序的数组A和B分别含有m和n个数,找到两个排序数组的中位数,要求时间复杂度应为O(log (m+n))。
样例
给出数组A = [1,2,3,4,5,6] B = [2,3,4,5],中位数3.5
给出数组A = [1,2,3] B = [4,5],中位数 3
class Solution {
/**
* @param A: An integer array.
* @param B: An integer array.
* @return: a double whose format is *.5 or *.0
*/
public double findMedianSortedArrays(int[] A, int[] B) {
// write your code here
int len=A.length+B.length;
if(len%2==0){
return (findKth(A,0, B,0,len/2+1)+findKth(A,0, B,0,len/2))/2.0;
}else{
return findKth(A,0, B,0,len/2+1);
}
}
public static int findKth(int[] A,int startA,int[] B,int startB,int k){
if(startA>=A.length){
return B[startB+k-1];
}
if(startB>=B.length){
return A[startA+k-1];
}
if(k==1){
return Math.min(A[startA],B[startB]);
}
int A_key=startA+k/2-1<A.length?A[startA+k/2-1]:Integer.MAX_VALUE;
int B_key=startB+k/2-1<B.length?B[startB+k/2-1]:Integer.MAX_VALUE;
if(A_key<=B_key){
return findKth(A,startA+k/2, B,startB,k-k/2);
}else{
return findKth(A,startA, B,startB+k/2,k-k/2);
}
}
}