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:
    double findMedianSortedArrays(int A[], int m, int B[], int n) {
        if((m+n)%2==1)
            return find(A,m,B,n,(m+n)/2+1);
        else
            return (find(A,m,B,n,(m+n)/2)+find(A,m,B,n,(m+n)/2+1))/2.0;
    }
    double find(int* A,int m,int* B,int n,int order)
    {
        if(m==0)
            return B[order-1];
        if(n==0)
            return A[order-1];
        if(order==1)
            return A[0]<B[0]?A[0]:B[0];       
            
        int mcheck=m>(order/2)?order/2:m;
        int ncheck=n>(order/2)?order/2:n;
        if(A[mcheck-1]<B[ncheck-1])
                return find(A+mcheck,m-mcheck,B,n,order-mcheck);
            else
                return find(A,m,B+ncheck,n-ncheck,order-ncheck);
    }
}; 
原文地址:https://www.cnblogs.com/erictanghu/p/3759161.html