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.
Credits:
Special thanks to @ts for adding this problem and creating all test cases.
The problem is to find a peak of the array, the peak can be a local maximum value, here to traverse the entire array to find the maximum value will definitely appear time Limit exceeded, we have to consider using similar to the binary lookup method to shorten the times, because just need to locate any one of the peaks, Then we determine the two points after the middle of the binary after the element, and immediately after the element compared to the size, if greater than, the peak is in front, if less than in the back. This will allow you to find a peak with the following code:
classSolution { Public: intFindpeakelement (Constvector<int> &num) { intleft =0; intright = Num.size ()-1; while(Left <=Right ) { if(left = right)returnRight ; intMiddle = (left + right)/2; if(Num[middle] < Num[middle +1]) left = middle +1; Elseright =Middle; } }};
[Leetcode] Find peak Element to find the peaks of an array