码迷,mamicode.com
首页 > 其他好文 > 详细

LeetCode 4 Median of Two Sorted Array

时间:2015-04-09 21:37:24      阅读:109      评论:0      收藏:0      [点我收藏+]

标签:

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到的数,但是这样算法的复杂度是o(nlogn),显然不符合题目的要求。

参考http://blog.csdn.net/zxzxy1988/article/details/8587244中的解法:

假设A,B两个数组元素都大于k/2。可以比较A[k/2]和B[k/2]

(1)A[k/2-1] < B[k/2-1] 此时可以判断A[0]~A[k/2]均比最终要找的median要小,可以去掉这部分元素。

(2)A[k/2-1] > B[k/2-1]此时可以判断B[0]~B[k/2]均比最终要找的median要小,可以去掉这部分元素。

(3)A[k/2-1] = B[k/2-1]此时判断要找的median就是A[k/2-1]orB[k/2-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;
		}
	}
	double findkth(int a[], int m, int b[], int n, int k)
   {
	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]);
	int idxA = min(k/2, m);
	int idxB = k - idxA;
	if(a[idxA - 1] < b[idxB-1])
	{
		return findkth(a+idxA, m-idxA, b, n, k- idxA);
	}
	else if(b[idxB-1] < a[idxA-1])
	{
		return findkth(a, m, b+ idxB, n - idxB, k - idxB );
	}
	else
		return a[idxA - 1];
   }
};

  使用的迭代,考虑到求解的方便使用:

if(m > n)
return findkth(b, n, a, m, k);//这句使得后面具体结果讨论省了一半,32个赞
if(m == 0)
return b[k-1];
if(k <= 1)
return min(a[0], b[0]);

对边界情况进行讨论。

多看多学习,不管怎样,这是个好时代,加油。

 

LeetCode 4 Median of Two Sorted Array

标签:

原文地址:http://www.cnblogs.com/bestwangjie/p/4411066.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!