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);
- Find the median of 2 sort ed array.
- [LintCode]Find Median of Unsorted Array O(n) quick sort
- 经典题find median of two sorted array
- quickly find the median of a sequence of numbers
- LeetCode-Median of sorted array(2)
- Find the first covering prefix of array
- Find the maxest element of an array
- 634. Find the Derangement of An Array
- Median of Two Sorted Array
- Median of two sorted array
- median of two sorted array
- median of two sorted array
- LeetCode-Median of sorted array
- Median of 5 element array.
- Median of two sorted array
- Ruby: how to sort array of string parsing the content
- Sort array of strings
- Given an array of integers, sort the array according to frequency of elements
- [VisualStudio]_[VS实用插件集合*持续更新]
- 【BZOJ】【P1013】【JSOI2008】【球形空间产生器sphere】【题解】【高斯消元】
- sxstrace.exe 工具的解决办法
- tiny6410 蜂鸣器字符设备驱动<2>
- 跨框架弹层
- Find the median of 2 sort ed array.
- .Java的垃圾回收机制(GC)
- 把heritrix抓取的网页在eclipse里读进,然后写出文件时出现乱码
- update-rc.d使用
- ruby on rails 指导入门 http://ihower.tw/rails3/firststep.html
- 剖析网页从浏览器输入地址到加载完毕的全过程——建立连接
- 练习题(2)
- 并发管理器2——OPP的概念
- weblogic eclipse 运行web应用程序