Skip to content

Instantly share code, notes, and snippets.

@luoxiaoxun
Last active December 19, 2015 13:58
Show Gist options
  • Save luoxiaoxun/5965524 to your computer and use it in GitHub Desktop.
Save luoxiaoxun/5965524 to your computer and use it in GitHub Desktop.
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))..
C++:
class Solution {
public:
double findMedianSortedArrays(int A[], int m, int B[], int n) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
int k=m+n;
if(k&0x1) return findKth(A,m,B,n,k/2+1);
else return (findKth(A,m,B,n,k/2)+findKth(A,m,B,n,k/2+1))/2;
}
double findKth(int A[],int m,int B[],int n,int k){
if(m>n) return findKth(B,n,A,m,k);
if(m==0) return B[k-1];
if(k<=1) return min(A[0],B[0]);
int pa=min(k/2,m);
int pb=k-pa;
if(A[pa-1]<B[pb-1]) return findKth(A+pa,m-pa,B,n,k-pa);
else if(A[pa-1]>B[pb-1]) return findKth(A,m,B+pb,n-pb,k-pb);
else return A[pa-1];
}
};
Java:大数据通不过
public class Solution {
public double findMedianSortedArrays(int A[], int B[]) {
// Start typing your Java solution below
// DO NOT write main() function
int k=A.length+B.length;
if(k%2==1) return findKth(A,A.length,B,B.length,k/2+1);
else return (findKth(A,A.length,B,B.length,k/2)+findKth(A,A.length,B,B.length,k/2+1))/2;
}
public double findKth(int A[],int m,int B[],int n,int k){
if(m>n) return findKth(B,n,A,m,k);
if(m==0) return B[k-1];
if(k<=1) return Math.min(A[0],B[0]);
int pa=Math.min(k/2,m);
int pb=k-pa;
if(A[pa-1]<B[pb-1]) return findKth(Arrays.copyOfRange(A,pa,m),m-pa,B,n,k-pa);
else if(A[pa-1]>B[pb-1]) return findKth(A,m,Arrays.copyOfRange(B,pb,n),n-pb,k-pb);
else return A[pa-1];
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment