2014
03-22

# LeetCode-Median of Two Sorted Arrays[题解]

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

double findMedianSortedArrays(int A[], int m, int B[], int n)
{
int i=0, j=0, median = m+n;
double prev=0, last=0;

if(median<2)
{
if (m == 0 && n == 0) return 0;
if (m==1) return A[0];
else return B[0];
}

while ( (i+j) <= (median/2) )
{
prev = last;
if (i >= m) //如果A中的元素已经用完，直接取B数组
{
last=B[j];
j++;
}
else if (j>=n) //同上
{
last = A[i];
i++;
}
else if (A[i]<B[j]) //取A[i] 和 B[j] 中较小的
{
last = A[i];
i++;
}
else
{
last=B[j];
j++;
}
}

if ((median & 1) == 0) //偶数个
return (prev + last) / 2.0;
else //奇数个
return last;
}

double findKth(int a[], int m, int b[], int n, int k)
{
//always assume that m is equal or smaller than n
if (m > n)
return findKth(b, n, a, m, k);
if (m == 0)
return b[k - 1];
if (k == 1)
return min(a[0], b[0]);
//divide k into two parts
int pa = min(k / 2, m), pb = k - pa;
if (a[pa - 1] < b[pb - 1])
return findKth(a + pa, m - pa, b, n, k - pa);
else if (a[pa - 1] > b[pb - 1])
return findKth(a, m, b + pb, n - pb, k - pb);
else
return a[pa - 1];
}

class Solution
{
public:
double findMedianSortedArrays(int A[], int m, int B[], int n)
{
int total = m + n;
if (total & 0x1)
return findKth(A, m, B, n, total / 2 + 1);
else
return (findKth(A, m, B, n, total / 2)
+ findKth(A, m, B, n, total / 2 + 1)) / 2;
}
};

1. 换句话说，A[k/2-1]不可能大于两数组合并之后的第k小值，所以我们可以将其抛弃。
应该是，不可能小于合并后的第K小值吧

2. 老实说，这种方法就是穷举，复杂度是2^n，之所以能够AC是应为题目的测试数据有问题，要么数据量很小，要么能够得到k == t，否则即使n = 30，也要很久才能得出结果，本人亲测