A peak element is an element, which is greater than its neighbors.
Given an input array where num[i] ≠ num[i+1]
, the find a peak element and return its index.
The array may be contain multiple peaks, in this case return the index to any one of the peaks is fine.
May imagine 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.
Click to show spoilers.
Note:
Your solution should is in logarithmic complexity.
Problem-solving ideas: A look at complexity requirements, immediately think of binary search. If the intermediate element is greater than its adjacent successive elements, the left side of the intermediate element (containing the intermediate element) must contain a local maximum value. If the intermediate element is smaller than its adjacent successive elements, the right side of the intermediate element must contain a local maximum value. Java Code:
Public classSolution { Public intFindpeakelement (int[] nums) { intleft = 0, right = nums.length-1; while(Left <Right ) { intMid = left + (right-left)/2; if(Nums[mid] < nums[mid+1]) { left= Mid + 1; }Else{ Right=mid; } } returnLeft ; }}
Reference:
1. http://blog.csdn.net/u010367506/article/details/41943309
2. Https://leetcode.com/discuss/56031/java-short-and-neat-code-10-line
Leetcode Find Peak Element