Saturday, March 2, 2013

Median of Two Sorted Arrays

/*
Median of Two Sorted Arrays
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)).
*/
class Solution {
public:
    int findKthElement(int A[], int sa, int B[], int sb, int k){
      if((sa+sb) < k) return -100;
      if(sa==0) return B[k-1];
      if(sb==0) return A[k-1];
     
      if(A[sa-1]<=B[0]){
        if(sa>=k) return A[k-1];
        else return B[k-sa-1];
      }
      if(B[sb-1]<=A[0]){
        if(sb>=k) return B[k-1];
        else return A[k-sb-1];
      }
      if(k==1) return min(A[0],B[0]);
     
      int ma;
      int mb;
      int newSearch = k/2;
      if(sa<=sb){
      if(sa>=newSearch) ma = newSearch;
      else ma = sa;
      mb = k - ma;
      }
      else{
      if(sb>=newSearch) mb = newSearch;
      else mb = sb;
      ma = k-mb;
      }
     
      if(A[ma-1]==B[mb-1]) return A[ma-1];
     
      if(A[ma-1]<B[mb-1]){
        return findKthElement(A+ma, sa-ma, B, mb, k-ma);
      }
     
      if(A[ma-1]>B[mb-1]){
        return findKthElement(B+mb, sb-mb, A, ma, k-mb);
      }
    }
    double findMedianSortedArrays(int A[], int m, int B[], int n) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
        int totalSize = m+n;
        double result;
        int half = totalSize/2;
        if(totalSize%2==1){
           result = findKthElement(A, m, B, n, (totalSize+1)/2);
        }
        else{
           double first =  findKthElement(A, m, B, n, half+1);
           double second =  findKthElement(A, m, B, n, half);
           result = (first+second)/2;    
        }
        return result;
    }
};

No comments:

Post a Comment