Median of Sorted Arrays

(http://leetcode.com/2011/03/median-of-two-sorted-arrays.html)

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

double findMedian(int A[], int B[], int l, int r, int nA, int nB)
{
if (l > r)
return findMedian(B, A, max(, (nA+nB)/-nA), min(nB, (nA+nB)/), nB, nA);
int i = (l+r)/;
int j = (nA+nB)/ - i - ;
if (j >= && A[i] < B[j])
return findMedian(A, B, i+, r, nA, nB);
else if (j < nB- && A[i] > B[j+])
return findMedian(A, B, l, i-, nA, nB);
else
{
if ((nA+nB)% == )
return A[i];
else if (i > )
return (A[i]+max(B[j], A[i-]))/2.0;
else
return (A[i]+B[j])/2.0;
}
}

A O(m+n) solution:

bool findMedian(int A[], int B[], int nA, int nB)
{
assert(A && B && nA >= && nB >= ); bool odd = (nA + nB) % == ? true : false;
int medianIndex = (nA+nB)/;
if (odd == false)
medianIndex++; int i = ;
int j = ;
int count = ;
int pre = -;
int cur = -;
while (i < nA && j < nB)
{
count++;
if (A[i] < B[j])
{
if (count == medianIndex)
{
cur = A[i];
break;
}
pre = A[i];
i++;
}
else
{
if (count == medianIndex)
{
cur = B[i];
break;
}
pre = B[j];
j++;
}
}
if (i == nA)
{
cur = B[j+medianIndex-count-];
if (medianIndex-count > )
pre = B[j+medianIndex-count-];
}
else if (j == nB)
{
cur = A[i+medianIndex-count-];
if (medianIndex-count > )
pre = A[i+medianIndex-count-];
} if (odd == true)
return cur;
else
return (cur+pre)/2.0;
}
上一篇:Spring AOP 四大通知


下一篇:geotrellis使用(十)缓冲区分析以及多种类型要素栅格化