1. 程式人生 > >leetcode:Median of Two Sorted Arrays (找兩個序列的中位數,O(log (m+n))限制) 【面試演算法】

leetcode:Median of Two Sorted Arrays (找兩個序列的中位數,O(log (m+n))限制) 【面試演算法】

題目:

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

題意已只兩個有序的序列,找到他們的中位數,複雜度要求O(log (m+n))。

問題可以轉化成兩個有序序列找第num大的數,用類似二分的思想,用遞迴處理。

因為兩個序列是有序的,對比A和B第num/2個數大小,每次把小的序列刪掉num/2個數,能保證不會刪掉第num大的數,可以紙上驗證一下。

如果一個序列沒有num/2個數,那麼就比較兩個序列第min(n,m)個數的大小,這麼做能儘快刪掉一個序列所有元素,結束遞迴。

這麼做最壞情況複雜度是O(log (m+n)),也就是num遞迴到1。

double find(int A[],int m,int B[],int n,int del)
{
    if(m==0)return B[del-1];
    else if(n==0)return A[del-1];
    else if(del==1)return A[0]<B[0]?A[0]:B[0];
    int temp=del/2;
    if(min(m,n)<temp)temp=min(m,n);
    if(A[temp-1]>=B[temp-1])return find(A,m,B+temp,n-temp,del-temp);
    else return find(A+temp,m-temp,B,n,del-temp);
}

class Solution {
public:
    double findMedianSortedArrays(int A[], int m, int B[], int n) {
        int del=(n+m+1)/2;
        double temp=find(A,m,B,n,del);
        if((m+n)&1)return temp;
        else return (find(A,m,B,n,del+1)+temp)/2.0;
    }
};