leetCode_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)).


 

     找中间数,要注意当(m+n) 是奇数时,中间数为第(m+n)/2 +1 ,当(m+n)为偶数时,中间数为第(m+n)/2   和(m+n) 两数的平均。所以该题可以转换为在两个排序的数列中,寻找第K个数。

     时间复杂度为O(log (m+n)),考虑使用二分查找,在两个数组中对比A[half]和B[half], 然后裁剪小的一个数组,不断裁剪直到1)小的数组为空,此时输出大的数组的第k个数(注意裁剪数组时,K也会做相应的裁剪); 2)当k== 1 时 ,返回 min(A[0], B[0])

 

View Code
class Solution {
public:
    double findKthSortedArrays(int A[], int m, int B[], int n,int k){
        
        if(m > n) return findKthSortedArrays(B, n, A, m, k);
        if(0 == m) return B[k-1];
        if(1 == k) return A[0] < B[0] ? A[0] : B[0];
        
        int pa = k>>1 < m ? k>>1: m ;
        int pb = k - pa;
        if(A[pa -1] <= B[pb-1])
                return findKthSortedArrays(A+pa, m-pa, B, n,k-pa );
            else
                return findKthSortedArrays(A, m , B+pb, n-pb, k -pb) ;
        
    }
    double findMedianSortedArrays(int A[], int m, int B[], int n) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
        if(1== (m+n)%2)
                return findKthSortedArrays(A, m, B, n, (m+n)/2 + 1);
           else
                return (findKthSortedArrays(A, m, B, n, (m+n)/2 + 1) + findKthSortedArrays(A, m, B, n, (m+n)/2)) /2 ;
           
        
    }
};

 

posted @ 2013-03-28 11:53  冰点猎手  阅读(169)  评论(0编辑  收藏  举报