A Za, A Za, Fighting...

坚信:勤能补拙

2011好题 - 寻找俩已排好序数组的中位数

问题:
有两个已排好序的数组A和B,长度均为n,找出这两个数组的中间元素。要求时间代价为O(logn)

思路:
a. 比较自然的思路是归并算法,不过时间复杂度是O(n),无法满足题目要求

b.
http://www.binghe.org/2011/05/find-median/ )

Say the two arrays are sorted and increasing, namely A and B.
It is easy to find the median of each array in O(1) time.
Assume the median of array A is m and the median of array B is n.
Then,
1′ If m=n, then clearly the median after merging is also m, the algorithm holds.
2′ If m<n, then reserve the half of sequence A in which all numbers are greater than
m, also reserve the half of sequence B in which all numbers are smaller than n.
Run the algorithm on the two new arrays.
3′ If m>n, then reserve the half of sequence A in which all numbers are smaller than
m, also reserve the half of sequence B in which all numbers are larger than n.

Run the algorithm on the two new arrays.

Time complexity: O(logn)






posted on 2011-10-16 18:38 simplyzhao 阅读(436) 评论(0)  编辑 收藏 引用 所属分类: R_找工复习2011


只有注册用户登录后才能发表评论。
网站导航: 博客园   IT新闻   BlogJava   博问   Chat2DB   管理


导航

<2012年2月>
2930311234
567891011
12131415161718
19202122232425
26272829123
45678910

统计

常用链接

留言簿(1)

随笔分类

随笔档案

搜索

最新评论

阅读排行榜

评论排行榜