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)).
思路:問題本質其實就是求兩個有序數組的第Kth的數,那麼我們可以這樣考慮,分別求出a,b兩個數組中第k/2th的數,這兩個數有三種情況
當a[k/2]<b[k/2]時,那麼原kth數肯定不在a[k/2]之前的數內,然後拋棄a[k/2]之前的所有數,再在剩餘的數裏求k-(k/2)th數,其餘兩種情況同理,遞歸二分,所以複雜度降到對數級別
double find_kth(int a[],int m,int b[],int n,int k){
if(m>n)
return find_kth(b,n,a,m,k);
if(m==0)
return b[k-1];
if(k==1)
return min(a[0],b[0]);
int pa=min(k/2,m),pb=k-pa;
if(a[pa-1]<b[pb-1])
return find_kth(a+pa,m-pa,b,n,k-pa);
else if(a[pa-1]>b[pb-1])
return find_kth(a,m,b+pb,n-pb,k-pb);
else
return a[pa-1];
}
class Solution {
public:
double findMedianSortedArrays(int A[], int m, int B[], int n) {
int sum=m+n;
if(sum%2){
return find_kth(A,m,B,n,sum/2+1);
}
else
return (find_kth(A,m,B,n,sum/2)+find_kth(A,m,B,n,sum/2+1))/2;
}
};