Median of Two Sorted Arrays
來(lái)源:程序員人生 發(fā)布時(shí)間:2014-11-03 08:23:24 閱讀次數(shù):2687次
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)).
題意:尋覓兩個(gè)有序數(shù)組的中位數(shù),要求復(fù)雜度為O(log
(m+n)).
思路:?jiǎn)栴}本質(zhì)其實(shí)就是求兩個(gè)有序數(shù)組的第Kth的數(shù),那末我們可以這樣斟酌,分別求出a,b兩個(gè)數(shù)組中第k/2th的數(shù),這兩個(gè)數(shù)有3種情況
當(dāng)a[k/2]<b[k/2]時(shí),那末原kth數(shù)肯定不在a[k/2]之前的數(shù)內(nèi),然后拋棄a[k/2]之前的所有數(shù),再在剩余的數(shù)里求k-(k/2)th數(shù),其余兩種情況同理,遞歸2分,所以復(fù)雜度降到對(duì)數(shù)級(jí)別
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;
}
};
生活不易,碼農(nóng)辛苦
如果您覺(jué)得本網(wǎng)站對(duì)您的學(xué)習(xí)有所幫助,可以手機(jī)掃描二維碼進(jìn)行捐贈(zèng)