您的位置:首页 > 其它

Median of Two Sorted Arrays

2013-06-03 11:36 246 查看
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)).

http://leetcode.com/onlinejudge#question_4

复杂度没有达到要求的log(m+n) 而是O(m+n),就这还写了半天呢,妈蛋!

class Solution
{
public:
double findMedianSortedArrays(int A[], int m, int B[], int n)
{
double ans=0;
int mid;
if((m+n)%2!=0)
{
mid=(m+n)>>1;
int i=0,j=0;
while((i+j)<=mid)
{
if(i>=m||m==0)
ans=B[j++];
else if(j>=n||n==0)
ans=A[i++];
else
{
if(A[i]<=B[j])
ans=A[i++];
else
ans=B[j++];
}
}
return ans;
}
else
{
mid=(m+n)>>1;
int i=0,j=0;
double tmp=0;
while((i+j)<=mid)
{
tmp=ans;
if(i>=m||m==0)
ans=B[j++];
else if(j>=n||n==0)
ans=A[i++];
else
{
if(A[i]<=B[j])
ans=A[i++];
else
ans=B[j++];
}
}
return (tmp+ans)/2;
}
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: