Friday, February 15, 2013

[LeetCode] Median of Two Sorted Arrays


Thought:
    The O(m+n) solution is trivial. However, we could improve it to O(lg(m+n)) by using kind of divide and conquer method.
    The key is to note that: when we remove the same amount of values from the start and end of a sorted array, its median remains the same.
    We could directly compare the median of array A and array B( respectively A[i] and B[j]) in O(1) time, and then remove some values before A[i] and after B[j](or before B[j] and after A[i]---- it depends on the size of A and B actually). By this way, we quickly decrease the problem size.
    While the most difficult part of this problem is to consider the base case and code them out. Believe in yourself and code them out!

Code(all the max and min method could be expanded to be easier to understand):
public class Solution {
    public double findMedianSortedArrays(int A[], int B[]) {
        double result = 0;
        int m = A.length;
        int n = B.length;
        if( m == 0 ){
            result = B[n/2] + B[(n-1)/2];
            result = result/2;
        }else if( n == 0 ){
            result = findMedianSortedArrays(B, A);
        }else if( m == 1 ){
            if( n%2 == 0 ){
                result = Math.min( B[n/2], Math.max(A[0], B[n/2-1]) );                 
            }else{
                if( n == 1 ){
                    result = A[0] + B[0];
                }else{
                    result = B[n/2] + Math.min( B[n/2+1], Math.max(A[0], B[n/2-1]) );  
                }
                result = result/2;
            }
        }else if( n == 1 ){
            result = findMedianSortedArrays(B, A);
        }else if( m == 2){
            if( n == 2 ){
                result = Math.max(A[0],B[n/2-1]) + Math.min(A[1],B[n/2]);
                result = result/2;
            }else if( n%2 == 0 ){
                result = Math.max(B[n/2-2], Math.min(A[1], B[n/2])) + Math.min(B[n/2+1], Math.max(A[0],B[n/2-1]));
                result = result/2;            
            }else{
                result = Math.max(B[n/2-1], Math.min(B[n/2+1], Math.max(A[0], Math.min(B[n/2], A[1]))));
            }
        }else if( n == 2){
            result = findMedianSortedArrays(B, A);
        }else{
            int temp = (Math.min(m, n)-1)/2;
            if(A[m/2] < B[n/2]){                
                A = Arrays.copyOfRange(A, temp, m);
                B = Arrays.copyOfRange(B, 0, n-temp); 
            }else{
                A = Arrays.copyOfRange(A, 0, m-temp);
                B = Arrays.copyOfRange(B, temp, n);
            }
            result = findMedianSortedArrays(A, B);
        }
        return result;
    }
}

No comments:

Post a Comment