您的位置:首页 > 其它

Find the median of 2 sort ed array.

2014-05-03 20:40 363 查看
转自:http://www.careercup.com/question?id=5762888694235136

Question:

从两个已排序的数组中找到中位数。要求算法复杂度小于O(n)。

Answer:

I had an O(logn) algorithm, posted in the original question.

Let X be the median of the first list, Y be the median of the second list. We can find X, Y in O(1) time, since lists are SORTED.


[code]L1 = {-------X-------}
L2 = {-------Y-------}


We have: numbers in the left of X (or Y) are not bigger than X (or Y); and the number in the right of X (or Y) are not smaller than X (or Y).

So, if X == Y we can conclude that the median should be equal to X.

If X < Y, the median cannot be in the left of X, and cannot be in the right of Y. Thus we can eliminate the left side of X and right side of Y, and recursively do for two remaining lists.

If X > Y, we eliminate the right side of X and left side of Y, and recursively do for two remaining lists.

We can stop when each list remains no more than 2 numbers, and find the median separately, in constant time. (I chose 2 to avoid boundary cases, you can choose 1 if you want).

This WORKs because each time we eliminate the same number of elements in right side and in left side, thus makes sure that the median always stays in the remaining lists.

This takes O(logn) because each time we eliminate half of the numbers...

Pseudo code may look like:
[code]findMedian(st1, ed1, st2, ed2):
{
	if (ed1-st1 <=2 ) return find_Median_By_Hand(st1, ed1, st2, ed2);

	mid1 = (st1+ed1)/2;
	X = L1[mid1];

	mid1 = (st2+ed2)/2;
	Y = L2[mid2];

	if (X==Y) return X;
	else
	if (X>Y) return findMedian(st1, mid1, mid2, ed2);
	else
	if (X<Y) return findMedian(mid1, ed1, st2, mid2);
}

The answer is:
res = findMedian (0, n, 0, n);
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐