Wednesday, August 6, 2014

Median of Two Sorted Arrays

This problem seems very simple, or straightforward at first glance. But the time complexity requirement is a little bit tough. Obviously, this should be related to binary search. Follow this route, I began to think how to apply this kind of "Divide and Conquer" method to it. I tried to solve it by looking at each mid element for each array, compare them, and then find out the "range" where median of the whole merged array can be found. For example, if A[AMid] < B[BMid], it means that elements before AMid in array cannot be median, and elements after BMid in array B cannot be median neither. Thus the value of median must be between A[AMid] and B[BMid]. However, this method is not  O(log(m + n)). Actually, I also tried other other methods like combining 2 arrays together, and tried to find median in the array of size ( m+n), but binary search cannot be applied.

Luckily, code_ganker got good solutions. I might came up with similar idea, but I just missed it. Hope that I can learn more from him, and solve similar questions by myself.




Thanks a lot to code_ganker for his explanation. Details about his post is here:
http://codeganker.blogspot.com/2014/02/median-of-two-sorted-arrays-leetcode.html

public double findMedianSortedArrays(int A[], int B[]) {
    if((A.length+B.length)%2==1)
        return helper(A,B,0,A.length-1,0,B.length-1,(A.length+B.length)/2+1);
    else
        return (helper(A,B,0,A.length-1,0,B.length-1,(A.length+B.length)/2)  
               +helper(A,B,0,A.length-1,0,B.length-1,(A.length+B.length)/2+1))/2.0;
}
private int helper(int A[], int B[], int i, int i2, int j, int j2, int k)
{
    int m = i2-i+1;
    int n = j2-j+1;
    if(m>n)
        return helper(B,A,j,j2,i,i2,k);
    if(m==0)
        return B[j+k-1];
    if(k==1)
        return Math.min(A[i],B[j]);
    int posA = Math.min(k/2,m);
    int posB = k-posA;
    if(A[i+posA-1]==B[j+posB-1])
        return A[i+posA-1];
    else if(A[i+posA-1]<B[j+posB-1])
        return helper(A,B,i+posA,i2,j,j+posB-1,k-posA);
    else
        return helper(A,B,i,i+posA-1,j+posB,j2,k-posB);
}

No comments:

Post a Comment