Median of Two Sorted Arrays
來源:程序員人生 發布時間:2014-11-03 08:23:24 閱讀次數:2683次
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的數,這兩個數有3種情況
當a[k/2]<b[k/2]時,那末原kth數肯定不在a[k/2]之前的數內,然后拋棄a[k/2]之前的所有數,再在剩余的數里求k-(k/2)th數,其余兩種情況同理,遞歸2分,所以復雜度降到對數級別
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⑴];
if(k==1)
return min(a[0],b[0]);
int pa=min(k/2,m),pb=k-pa;
if(a[pa⑴]<b[pb⑴])
return find_kth(a+pa,m-pa,b,n,k-pa);
else if(a[pa⑴]>b[pb⑴])
return find_kth(a,m,b+pb,n-pb,k-pb);
else
return a[pa⑴];
}
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;
}
};
生活不易,碼農辛苦
如果您覺得本網站對您的學習有所幫助,可以手機掃描二維碼進行捐贈