【问题标题】:Peak finding algorithm MIT OCW 6.006 - Does it always exist?寻峰算法 MIT OCW 6.006 - 它总是存在吗?
【发布时间】:2020-04-27 12:24:06
【问题描述】:

这周我开始了 MIT OCW 6.006 讲座,在第一堂课中教授介绍了寻峰算法。

http://ocw.mit.edu/courses/electrical-engineering-and-computer-science/6-006-introduction-to-algorithms-fall-2011/lecture-videos/MIT6_006F11_lec01.pdf

根据他的定义:

[a b c d e f g h i]
1 2 3 4 5 6 7 8 9
a-i 是数字

当且仅当 b ≥ a 且 b ≥ c 时,位置 2 才是峰值。如果 i ≥ h,则位置 9 是一个峰值

他提出这个算法来提高它的复杂度:

If a[n/2] < a[n/2 − 1] then only look at left half 1 . . . n/2 − − − 1 to look for peak
• Else if a[n/2] < a[n/2 + 1] then only look at right half n/2 + 1 . . . n to look for peak
• Else n/2 position is a peak: WHY?
    a[n/2] ≥ a[n/2 − 1]
    a[n/2] ≥ a[n/2 + 1]

但是,如果我有这个示例数组怎么办:

[9,8,7,6,5,2,3,1]

算法会这样工作:

第 1 步:a[n/2] 6 是的,看左半边 [9,8,7,6]
第 2 步:a[n/2] 8 是的,看左半边 [9,8]
第三步:???

虽然有一个峰值,但不会找到峰值:[9,8,7,6,5,2,3,1]

我想我错过了一些东西,但我没有弄清楚。有人可以解释一下为什么它不起作用?

我找到了这个相关的问题,但没有答案:Peak finding algorithm

【问题讨论】:

  • 在您的示例中,峰值为 9。该算法假设存在一个峰值。
  • 他假设只有尾部可以是峰。 “当且仅当 b ≥ a 且 b ≥ c 时,位置 2 才是峰值。如果 i ≥ h,位置 9 才是峰值”。他没有说“如果 a ≥ b,位置 1 是一个峰值”。
  • 是的,但我认为这只是一个疏忽。该算法正在检查斜率,并朝着增加值的方向移动。所以它会在数组的两端找到一个峰值。
  • 算法 确实 似乎对像 [1,2,2,2,2,3] 这样的数组有问题,因为它会声明 2 是一个峰值,当不是。

标签: algorithm language-agnostic


【解决方案1】:

你必须自己考虑边界条件。
这是完整的步骤:

Step 1: a[n/2] < a[n/2-1]? --> 6 < 7? --> yes, look at left half [9,8,7,6]
Step 2: a[n/2] < a[n/2-1]? --> 8 < 9? --> yes, look at left half [9,8]
Step 3: ??? <br>
//if you put a check on boundary condition then
Step 3: a[n/2] > a[n/2+1]? --> 9 > 8? --> yes, look at right half [8]
Step 4: loop terminates as only one element is left(it is a peak)

您可以找到更好的问题描述 here.

【讨论】:

    猜你喜欢
    • 2013-09-26
    • 1970-01-01
    • 1970-01-01
    • 2010-12-15
    • 1970-01-01
    • 2021-07-23
    • 1970-01-01
    • 1970-01-01
    • 2012-03-19
    相关资源
    最近更新 更多