There are two sorted arrays A and B of size m and n respectively. Find the median of the two sorted arrays. The overall run time complexity should be O(log (m+n)).
class Solution { public: int FindKthElm(int A[],int bA,int eA,int B[],int bB,int eB,int k){ if(bA>eA){ return B[bB+k-1]; } if(bB>eB){ return A[bA+k-1]; } int mA=(bA+eA)/2; int mB=(bB+eB)/2; int half=mA-bA+mB-bB+2; if(A[mA]>B[mB]){ //此时B数组和第k元素都在A[mA]左侧,A[mA]到A[eA]可以舍弃 if(k<half){ return FindKthElm(A,bA,mA-1,B,bB,eB,k); } //此时k元素及A数组都在B[mB]右侧,B[bB]到B[mB]可以舍弃 else{ return FindKthElm(A,bA,eA,B,mB+1,eB,k-(mB-bB+1)); } } else if(A[mA]==B[mB]){ if(k<=half-2){ return FindKthElm(A,bA,mA-1,B,bB,mB-1,k); } else if(k>half){ return FindKthElm(A,mA+1,eA,B,mB+1,eB,k-(half)); } else return A[mA]; } else{ //此时A数组和第k元素都在B[mB]左侧,B[mB]到B[eB]可以舍弃 if(k<half){ return FindKthElm(A,bA,eA,B,bB,mB-1,k); } //此时k元素及B数组都在A[mA]右侧,A[bA]到A[mA]可以舍弃 else{ return FindKthElm(A,mA+1,eA,B,bB,eB,k-(mA-bA+1)); } } } double findMedianSortedArrays(int A[], int m, int B[], int n) { int total=m+n; if(total==0)return 0; if(total%2==0){ int index1=total/2+1; int index2=index1-1; int val1=FindKthElm(A,0,m-1,B,0,n-1,index1); int val2=FindKthElm(A,0,m-1,B,0,n-1,index2); return (val1+val2)/2.0; } else{ return FindKthElm(A,0,m-1,B,0,n-1,total/2+1); } } };
public class Solution { public int FindKth(int A[],int B[],int sa,int ea,int sb,int eb,int k){ if(sa>ea){ return B[sb+k-1]; } else if(sb>eb){ return A[sa+k-1]; } else{ int midA=(sa+ea)/2; int midB=(sb+eb)/2; int half=midA-sa+midB-sb+2; if(A[midA]>B[midB]){ if(k<half)return FindKth(A,B,sa,midA-1,sb,eb,k); else return FindKth(A,B,sa,ea,midB+1,eb,k-(midB-sb+1)); } else if(A[midA]<B[midB]){ if(k<half)return FindKth(A,B,sa,ea,sb,midB-1,k); else return FindKth(A,B,midA+1,ea,sb,eb,k-(midA-sa+1)); } else{ if(k>half){ k-=half; return FindKth(A,B,midA+1,ea,midB+1,eb,k); } else if(k<half-2){ return FindKth(A,B,sa,midA-1,sb,midB-1,k); } else return A[midA]; } } } public double findMedianSortedArrays(int A[], int B[]) { // Note: The Solution object is instantiated only once and is reused by // each test case. int total=A.length+B.length; if(total==0)return 0; if(total%2==0){ int p1=FindKth(A,B,0,A.length-1,0,B.length-1,total/2); int p2=FindKth(A,B,0,A.length-1,0,B.length-1,total/2+1); return (p1+p2*1.0)/2; } else{ return FindKth(A,B,0,A.length-1,0,B.length-1,total/2+1); } } }