【问题标题】:divide and conquer - finding the median for an array分而治之 - 找到数组的中位数
【发布时间】: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


【解决方案1】:

选择(其中中位数计算是一种特殊情况)无法在 O(log n) 时间内解决。您可以使用 Quickselect 等算法在 O(n) 时间内解决它。

【讨论】:

  • 如果您使用median of medians 选择枢轴,您会得到 O(n),前面有一个较大的常数。这是因为中位数算法保证返回第 30 和第 70 个百分位数之间的值,因此最坏情况下的性能是 T(n) = O(n) + T(n/5) + T(0.7n) = O(n)。
猜你喜欢
  • 2017-03-23
  • 2020-01-07
  • 2018-01-26
  • 2015-05-03
  • 2013-01-16
  • 1970-01-01
  • 1970-01-01
  • 2014-03-25
  • 2017-06-07
相关资源
最近更新 更多