您的位置:首页 > 编程语言 > C语言/C++

LeetCode刷题之第二题——Median of Two Sorted Arrays

2015-02-07 13:41 459 查看
原题:

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

翻译:

这里有A、B两个已排序数组,数组大小分别为m和n,找到这两个排序数组的中位数,要求整体的时间复杂度为O(log
(m+n))。

解决:

从题中来看,最简单的方法,无非是将这个数组进行合并排序,然后找到其中位数,但是这个实际耗费时间巨大,难以满足题目需求。

解决方案一:

对两个数组分别设置一个计数指示,分别为pa和pb,然后依次从头开始比较两个数组,无论谁大对应的计数指示加1,等到pa+pb==(m+n)/2+1时,返回对应的那个值,即为所需求的中位数(这里是相对于m+n的结果为奇数而言的,实际上为偶数的话也类似),不过这种解法的时间复杂度为O(m+n),同样无法满足题中要求;

解决方案二:

实际上,当看到复杂度是log级别的时候,一个很自然的想法是分治方法,而查找两个排序数组的中位数命题实际上也等同于寻找到该两个数组的第(m+n)/2+1 小的数,因此可采用通用的寻找两个已排序数组的第kth小的数的方法来解决问题,该相关内容在下面的帖子中描述非常详细:
http://blog.csdn.net/beiyeqingteng/article/details/7533304
因此本题的解决方案为:

4 class Solution {
5 public:
6 double findkth(int A[], int m, int B[], int n, int k) {
7 if (m > n)
8 return findkth(B, n, A, m, k);
9 if (m == 0)
10 return B[k-1];
11 if (k == 1)
12 return min(A[0], B[0]);
13 int pa = min(k/2, m);
14 int pb = k - pa;
15 if (A[pa-1] < B[pb-1])
16 return findkth(A+pa, m-pa, B, n, k-pa);
17 else if (A[pa-1] > B[pb-1])
18 return findkth(A, m, B+pb, n-pb, k-pb);
19 else
20 return A[pa-1];
21 }
22
23 double min(int x, int y)
24 {
25 return x > y ? y : x;
26 }
27
28 double findMedianSortedArrays(int A[], int m, int B[], int n) {
29 int total = m + n;
30 if (total & 0x1)
31 return findkth(A, m, B, n, total/2+1);
32 else
33 return (findkth(A, m, B, n, total/2) + findkth(A, m, B, n, total/2+1))/2;
34 }
35 };
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  leetcode c++