【发布时间】:2014-03-24 01:39:06
【问题描述】:
假设我们有一个包含所有唯一元素的大小为 2n 的数组。
假设我们将数组分成大小为 n 的 2 个数组,并且如果 1
那么求中位数的 Θ(log(n)) 算法是什么?中位数定义为 2 个数组之间的第 n 个最低元素。如果数组是 [1 2 3 4 5 6],中位数通常是 (3+4)/2,但我们只选择较小的一个,即 3。 我的尝试即:
2n = 6 [1 2 3 4 5 6]
n = 3 [1 2 3] [4 5 6] (not necessarily sorted, but we have the constant time lookup, so sorting is irrelevant)
Step 1) use lookup where k = n to find the kth smallest element for each array
[1 2 3] [4 5 6]
^ ^ (if k = 3, we get 3 for the first array, 6 for the second array)
Step 2) compare the 2 values we got and choose the smaller one. 3 is the median where median is defined as the nth lowest element between the 2 arrays.
首先,这是 Θ(log(n)) 时间的正确算法吗?其次,证明正确性(它找到中位数)是什么样的?我相信这将是通过归纳。
【问题讨论】:
-
Assume [...] we have a special constant time lookup to find the kth smallest element for that particular array if 1 <= k <= n这对我来说听起来像是一个很大的假设...... -
如果将数组拆分为 [1 2 6] [3 4 5],那么您的算法将返回 5。因此它不可能是正确的。
-
哦,你是对的,@HugoRune。
标签: algorithm proof divide-and-conquer