可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
I recently started looking at MIT's 6.006 lectures and in the first lecture the instructor presented peak-finding algorithm.
http://ocw.mit.edu/courses/electrical-engineering-and-computer-science/6-006-introduction-to-algorithms-fall-2011/lecture-videos/MIT6_006F11_lec01.pdf
According to his definitions:
Given an array [a,b,c,d,e,f,g] where a-g are numbers, b is a peak if and only if a = c.
He gave a recursive approach:
if a[n/2]
He said the algorithm is T(n) = T(n/2) + o(1) = o(lgn)
In his pdf he also gave a complete example: [6,7,4,3,2,1,4,5]
Both 7 and 5 are peaks. But doesn't the algorithm above only finds 7 as peak just because the middle element happens to satisfy the first branch?
So if we were supposed to find all the peaks, would we still be walking through the entire array? Would it mean worst case N?
Does his definition implies we just need to find a single peak?
I believe this problem can be viewed as finding the maximum and minimum element in Riverst's Introduction to Algorithm book.
回答1:
Yes, this algorithm only finds a single peak.
If you want to find all the peaks you have to check all the elements, so it's going to be O(n).
Note: a peak is not necessarily a global maximum.
回答2:
I am not quite convinced if this algorithm is the best way to find an interesting peak. It tends to favor the comparison at middle element which might drive the search to suboptimal direction and eventually the algorithm would always end up in finding peak at Edges and not in the middle. Simple example
[1,2,3,4,5,6,7,8] => Peak would be 8
[6,21,7,8,9,10,11,13] => Peak would be 13 while peak of 21 is more interesting
sure, the algorithm is guaranteed to find a peak because it moves in higher direction but as I show in the example, the peak may not be the interesting one!
回答3:
This algorithm looks quite similar to binary search algorithm. Binary search works only on sorted arrays, and this peak-searching algorithm looks like it is supposed to work with another definition: x[p]
is a peak if for 0 x[i] and for p x[i] >= x[i + 1]
. If we decide that the definition in the question is wrong, and this one is right: everything is OK. And it looks like it is wrong, because it gives several peaks in the second case, you are right.
回答4:
I just started this course yesterday, and the problem statement is:
Problem: Find a peak if it exists (Does it always exist?)
So, what the algorithm does is just trying to find a peak, the first one available, in the least time possible.
That's why this algorithm finds only a single peak.