http://leetcode.com/2011/03/median-of-two-sorted-arrays.html#comment-1053
Sophia's code has error, only can pass 1500 tests. briankwong's good, and based on MIT solution.
public class Solution {
public double findMedianSortedArrays(int A[], int B[]) {
// Start typing your Java solution below
// DO NOT write main() function
int alength = A.length;
int blength = B.length;
if (alength == 0 ) {
if (blength % 2 == 1) {
return B[blength/2];
}
else {
return ( B[blength/2 - 1] + B[blength/2] ) / 2.0;
}
}
else if (blength == 0 ) {
if (alength % 2 == 1) {
return A[alength/2];
}
else {
return ( A[alength/2 - 1] + A[alength/2] ) / 2.0;
}
}
int left = Math.max(0, (alength + blength)/2 - blength);
int right = Math.min(alength-1, (alength + blength)/2);
return findMedian(A, B, left, right, alength, blength);
}
public double findMedian(int A[], int B[], int l, int r, int nA, int nB) {
if (l>r) {
int left = Math.max(0, (nA + nB)/2 - nA);
int right = Math.min(nB-1, (nA + nB)/2);
return findMedian(B, A, left, right, nB, nA);
}
int i = (l+r)/2;
int j = (nA+nB)/2-i-1;
System.out.println("j:" + j);
boolean lvalid = (j < 0) || (A[i] >= B[j]);
boolean rvalid = (j >= nB - 1) || (A[i] <= B[j + 1]);
if ( lvalid && !rvalid ) return findMedian(A, B, l, i-1, nA, nB);
else if (!lvalid && rvalid) return findMedian(A, B, i+1, r, nA, nB);
else {
if ( (nA+nB)%2 == 1 ) return A[i];
else if (i>0) {
if (j<0) {
return (A[i]+A[i-1])/2.0;
}
else {
return (A[i]+Math.max(B[j], A[i-1]))/2.0;
}
}
else return (A[i]+B[j])/2.0;
}
}
public static void main(String[] args) {
int i = 25;
System.out.println("i:" + i);
System.out.println("Math.round(i/2):" + Math.round(i/2));
Solution s = new Solution();
int[] A = new int[]{5};
int[] B = new int[]{1,2,3,4,6,7};
double c = s.findMedianSortedArrays(A, B);
System.out.println(c);
}
public double findMedianSortedArrays2(int A[], int B[]) {
int m = A.length, n = B.length;
if(m == 0) return simpleMedian(B);
if(n == 0) return simpleMedian(A);
return medianSearch(A, B, Math.max(0, (m + n)/2 - n), Math.min(m - 1, (m + n)/2));
}
private double medianSearch(int A[], int B[], int left, int right){
int m = A.length, n = B.length;
if(left > right) return medianSearch(B, A, Math.max(0, (m + n)/2 - m), Math.min(n - 1, (m + n)/2));
int i = (left + right) / 2;
int j = (m + n) / 2 - i - 1;
boolean lvalid = (j < 0) || (A[i] >= B[j]);
boolean rvalid = (j >= n - 1) || (A[i] <= B[j + 1]);
if(lvalid && !rvalid){
return medianSearch(A, B, left, i - 1);
}else if(!lvalid && rvalid){
return medianSearch(A, B, i + 1, right);
}
// median is found
if((m + n) % 2 == 1) return A[i];
if(i > 0) {
int pre = (j < 0) ? A[i - 1] : Math.max(A[i - 1], B[j]);
return (A[i] + pre) / 2.0;
}
return (A[i] + B[j]) / 2.0;
}
private double simpleMedian(int A[]){
int n = A.length;
if(n % 2 == 1) return A[n/2];
return (A[n/2 - 1] + A[n/2]) / 2.0;
}
}