Find Peak Element

A peak element is an element that is greater than its neighbors.

Given an input array where num[i] ≠ num[i+1], find a peak element and return its index.

The array may contain multiple peaks, in that case return the index to any one of the peaks is fine. You may imagine that num[-1] = num[n] = -∞. For example, in array [1, 2, 3, 1], 3 is a peak element and your function should return the index number 2.

Binary search. If mid is the peak, return it. If mid is not the peak, it must be less than or equal to one of its neighbors. Suppose it is less than or equal to its left, then the left half must contains a peak. Why? If the left half is not monotonically decreasing, there must contains a peak. If the left half is monotonically decreasing, the peak is the first element.

Comments

Popular posts from this blog

Maximum Gap

[ITint5] Maximum Subarray for a Circular Array

[CC150] Chapter 8 Object-Oriented Design