Find Peak Element
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.
Problem Solving Ideas:
This problem is quite simple, just return one of the peaks. You can scan an array at most once. The authorities say dichotomy, which I think is as efficient as the array is randomly arranged. Pay attention to the handling of special cases.
Class Solution {public: int findpeakelement (const vector<int> &num) { int len=num.size (); Handling Special Cases if (len==0| | Len==1) { return 0; } if (Num[0]>num[1]) { return 0; } if (Num[len-1]>num[len-2]) { return len-1; } for (int i=1; i<len-1; i++) { if (num[i]>num[i-1]&&num[i]>num[i+1]) { return i; } } return 0;} };
[Leetcode] Find Peak Element