您的位置:首页 > 其它

Median of Two Sorted Arrays 分类: Leetcode(线性表) 2015-02-04 09:05 54人阅读 评论(0) 收藏

2015-02-04 09:05 399 查看


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

这道题又是一道需要仔细想的题,一开始最容易想的是直接排好序后取第k(k=(m+n)/2)大的值就行了, 不过这样无法满足题目要求的复杂度。还是另一种算法给力,有种二分法的味道。为了方便理解

对于A,B数组,我们直接比较A[k/2-1]和B[k/2-1],这样就有三种情况

1.A[k/2-1] < B[k/2-1] , 这说明第k个值一定不在A数组的前k/2个元素中,为什么呢,因为假设我们合并了A,B数组并排好序组成数组C,那么前k/2-1个A中的元素一定在C的0到k中。因为C的k个元素全部由A和B组成,而A[k/2-1] < B[k/2-1],所以A[k/2-1]最前出现在C[k/2-1]最后出现在C[k-2],这说明第k个元素肯定不在A数组的前k/2个元素中。我们也可以用反证法证明,假设A[k/2-1]是第k大的值,但是A中小于k的元素个数至多2/k-1 + B中小于k的元素个数至多k/2
-1 = k-2 显然 A[k/2-1]至多只能是第k-1大的值,矛盾。

2.A[k/2-1] > B[k/2-1],与1类似同理

3.A[k/2-1] = B[k/2-1] 此时两个值相等,k/2-1就是我们要的值

还需要考虑的一些特殊情况:

1.m > n

2.m == 0

3.k == 1

4.k/2 > m

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

private:
static int find_kth(int A[], int m, int B[], int n, int k){
if(m > n) return find_kth(B, n, A, m, k);
if(m == 0) return B[k-1];
if(k == 1) return min(A[0], B[0]);

int pa = min(k/2, m);
int pb = k - pa;
if(A[pa-1] < B[pb-1])
return find_kth(A+pa, m - pa, B, n, k-pa);
else if(A[pa-1] > B[pb-1])
return find_kth(A, m , B+pb, n-pb, k-pb);
else
return A[pa-1];
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐