Find the median of 2 sort ed array.

来源:互联网 发布:论坛推广软件 编辑:程序博客网 时间:2024/05/21 00:46

转自: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.

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:

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;elseif (X>Y) return findMedian(st1, mid1, mid2, ed2);elseif (X<Y) return findMedian(mid1, ed1, st2, mid2);}The answer is:res = findMedian (0, n, 0, n);

0 0
原创粉丝点击