您的位置:首页 > 其它

LeetCode Median of Two Sorted Arrays

2012-11-20 15:41 501 查看
Median of Two Sorted Arrays

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



Tips:

http://www.mitbbs.com/article/JobHunting/32203731_0.html

Solution:
class Solution {
public:
int findKth(int A[],int m,int B[],int n,int k){
if(m>n)
return findKth(B,n,A,m,k);
if(m==0)
return B[k];
if(k==0)
return min(A[0],B[0]);
int pa=min((k+1)/2,m),pb=k-pa+1;
if(A[pa-1]<B[pb-1])
return findKth(A+pa,m-pa,B,n,k-pa);
return findKth(A,m,B+pb,n-pb,k-pb);
}

double findMedianSortedArrays(int A[], int m, int B[], int n) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
return (findKth(A,m,B,n,(m+n)/2)+findKth(A,m,B,n,(m+n-1)/2))*1.0/2;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: