Leetcode Median of Two Sorted Arrays

OpenSoucre發表於2014-03-24

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

將兩個有序陣列合並,注意題目求得是the median of the two sorted array,

當m+n是奇數時返回的是合併後的中間數即C[(m+n)/2]

當m+n是偶數時返回的是合併後的中間兩個數的平均數即(C[(m+n)/2]+C[(m+n)/2-1]+0.0)/2

注意題目求的是double,空間複雜度是O(m+n)

#include <iostream>
#include <vector>
#include <algorithm>

using namespace std;

double findMedianSortedArrays(int  A[], int m, int B[],int n){
    int *C = new int[m+n],i=0,j=0,k = 0;
    while(i < m && j < n ){
        if(A[i] > B[j]) C[k++]=B[j++];
        else if(A[i] < B[j]) C[k++] = A[i++];
        else { C[k++]=A[i++];C[k++] = B[j++];}
    }
    if(i < m ){
        for(int idx = i ; idx < m ; idx++) C[k++] = A[idx];
    }
    if( j< n){
        for(int idx = j; idx < n; idx++) C[k++] =  B[idx];
    }
    double mid = double(C[(m+n)/2]);
    if((m+n)%2 == 0) mid = (C[(m+n)/2]+C[(m+n)/2-1]+0.0)/2;
    delete [] C;
    return mid;
}

int main(){
    int A[] ={1,3} ;
    int B[] = {2};
    cout<<findMedianSortedArrays(A,2,B,1)<<endl;
}

 利用二分查詢,時間複雜度O(log(m+n))

#include <iostream>
#include <algorithm>

using namespace std;

double findKth(int A[], int m, int B[], int n , int k){
    if(m > n){
        return findKth(B,n,A,m,k);
    }else{
        if( m == 0 ) return B[k-1];
        if( k == 1 ) return min(A[0],B[0]);
        int first = min(k/2,m),second = k - first;
        if( A[first- 1] <  B[second-1])
            return findKth(A+first,m-first,B,n,k-first);
        else if(A[first-1] > B[second-1])
            return findKth(A,m,B+second,n-second,k-second);
        else return A[first-1];
    }
}

double findMedianSortedArrays(int A[], int m, int B[], int n){
    int total = m + n;
    if(total & 0x1)
        return findKth(A,m,B,n,(total>>1)+1);
    else
        return (findKth(A,m,B,n,(total>>1)) + findKth(A,m,B,n,(total>>1)+1))/2;
}

int main(){
    int A[] ={1,2,2} ;
    int B[] = {1,2,3};
    cout<<findMedianSortedArrays(A,3,B,3)<<endl;
}

 

相關文章