您的位置:首页 > 其它

两个有序数组的中位数 Median of Two Sorted Arrays

2013-10-05 23:45 453 查看
Leetcode上的一道题:

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:
    double findMedianSortedArrays(int A[], int m, int B[], int n) {
        // Note: The Solution object is instantiated only once and is reused by each test case.
        assert(m+n > 0);
        bool isOdd = (m+n) % 2 ;
        if(0==m)
            if(isOdd)
                return B[n/2];
            else
                return (B[n/2-1]+B[n/2])/2.0;
        if(0==n)
            if(isOdd)
                return A[m/2];
            else
                return (A[m/2-1]+A[m/2])/2.0;
        if(isOdd)
        {
            return findKthMaxNumOfArrays(A,m,B,n,(m+n+1)/2);    
        }
        else
        {
            return (findKthMaxNumOfArrays(A,m,B,n,(m+n)/2)+findKthMaxNumOfArrays(A,m,B,n,(m+n)/2+1) )/2.0;  
        }
    }
    
    int findKthMaxNumOfArrays(int* A,int m,int* B,int n,int k)
    {
        if(0 == m)
            return B[k-1];
        if(0 == n)
            return A[k-1];
        int i=m>>1, j=n>>1, *p, *q, t;
        if(A[i] < B[j])
            p = A, q=B;
        else
        {   
            p=B;q=A;
            int tmp = i;
            i = j;
            j = tmp;
            tmp = n;
            n = m;
            m = tmp;
        }   
        t = i+j+1;
        if(t>=k)
            return findKthMaxNumOfArrays(p,m,q,j,k);
        else
            return findKthMaxNumOfArrays(p+i+1,m-i-1,q,n,k-i-1);
    }
};


参考:

http://www.cnblogs.com/XjChenny/p/3161592.html

这道题可以扩展为两个有序数组的第K大元素
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐