Problem
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)).
Code
double fmsa(int A[], int m, int B[], int n,int rank) {
// Note: The Solution object is instantiated only once and is reused by each test case.
if(n > m)
return fmsa(B,n,A,m,rank);
if(n == 0)
return A[rank - 1];
if(rank == 1)
return min(B[0],A[0]);
int k = min(n,rank/2);
if(A[k - 1] < B[k - 1]){
A += k;
m -= k;
}
else{
B += k;
n -= k;
}
rank -= k;
return fmsa(A,m,B,n,rank);
}
double findMedianSortedArrays(int A[], int m, int B[], int n) {
// Note: The Solution object is instantiated only once and is reused by each test case.
int rank = (m + n)/2;
if((m + n) % 2 == 0){
return ( fmsa(A,m,B,n,rank) + fmsa(A,m,B,n,rank + 1) )/2.0;
}
else
return fmsa(A,m,B,n,rank + 1);
}
No comments:
Post a Comment