1. 程式人生 > >兩個有序陣列的中位數 Median of Two Sorted Arrays

兩個有序陣列的中位數 Median of Two Sorted Arrays

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);
    }
};

參考:

這道題可以擴充套件為兩個有序陣列的第K大元素