您的位置:首页 > 其它

Median of Two Sorted Arrays

2014-04-14 14:31 281 查看
class Solution {
public:
double findMedianSortedArrays(int A[], int m, int B[], int n) {
double lhs=0,rhs=0;//lhs为第(m+n)/2大的数  rhs为第(m+n)/2+1大的数
//O(m+n)
int aIndex=0,bIndex=0,number=1,cur=0;
while(aIndex < m || bIndex < n)
{
if(aIndex < m && bIndex < n)
{
if(A[aIndex] <= B[bIndex])
{
cur=A[aIndex];
aIndex++;
}
else
{
cur=B[bIndex];
bIndex++;
}
}
else if(aIndex < m && bIndex >=n)
{
cur=A[aIndex];
aIndex++;
}
else
{
cur=B[bIndex];
bIndex++;
}
if(number==(m+n)/2)
{
lhs=(double)cur;
}
if(number==(m+n)/2+1)
{
rhs=(double)cur;
return ((m+n)%2)?rhs:(lhs+rhs)/2;
}
number++;
}
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  数组