分而治之找到一个高峰阵列应用的算法。分而治之、阵列、算法、高峰

由网友(涐会陪着你 不离不弃﹌)分享简介:对于数组A: 1 ,一个 2 ,…一个 K ,…一个 N ,一个 K 是一个高峰,当且仅当 K-1 和乐;一个 K ≥一个 K + 1 时1 LT; K和K&其中; ñ。一个 1 是一个高峰,如果 1 ≥一个 2 和 N 是一个高峰,如果 N-1 和乐;一个 N 。的目标是找到从...

对于数组A: 1 ,一个 2 ,…一个 K ,…一个 N ,一个 K 是一个高峰,当且仅当 K-1 和乐;一个 K ≥一个 K + 1 时1 LT; K和K&其中; ñ。一个 1 是一个高峰,如果 1 ≥一个 2 和 N 是一个高峰,如果 N-1 和乐;一个 N 。的目标是找到从阵列一个峰。

For an array a: a1, a2, … ak, … an, ak is a peak if and only if ak-1 ≤ ak ≥ ak+1 when 1 < k and k < n. a1 is a peak if a1 ≥ a2, and an is a peak if an-1 ≤ an. The goal is to find one peak from the array.

一个分而治之算法,给出如下:

A divide and conquer algorithm is given as follows:

find_peak(a,low,high):
    mid = (low+high)/2
    if a[mid-1] <= a[mid] >= a[mid+1] return mid // this is a peak;
    if a[mid] < a[mid-1] 
        return find_peak(a,low,mid-1) // a peak must exist in A[low..mid-1]
    if a[mid] < a[mid+1]
        return find_peak(a,mid+1,high) // a peak must exist in A[mid+1..high]

为什么这个算法是正确的?我觉得可能遭受损失的一半,其中存在一个峰值的数组。

Why this algorithm is correct? I think it may suffer from losing half of the array in which a peak exists.

推荐答案

该算法是正确的,虽然它需要一点微积分的证明。 第一种情况是琐碎和RARR;峰。 第二种情况是一个半峰,意思是它具有向下斜坡,而不是向上。

The algorithm is correct, although it requires a bit of calculus to prove. First case is trivial → peak. Second case is a "half peak", meaning that it has the down slope, but not up.

我们有两个可能的选择:

We have 2 possibilities here:

在该函数单调递减,直到一个中&RARR;一个 1 ≥一个 2 的高峰。 的功能并不单调递减的,直到一个中&RARR;有一个1≥k≥mid,对于其中 K ≥一个 K-1 。让我们选择的这这种说法是真RARR最大的K表;一个 K + 1 &LT;一个 K ≥一个 K-1 &RARR;这就是峰值。 The function is monotonically decreasing till amid → a1 ≥ a2 is the peak. The function is not monotonically decreasing till amid → There is a 1≥k≥mid, for which ak ≥ ak-1. Let's choose the largest k for which this statement is true → ak+1 < ak ≥ ak-1 → and that's the peak.

类似的参数可以应用于第三种情况与对面的半峰。

Similar argument can be applied for the third case with the opposite "half peak".

阅读全文

相关推荐

最新文章