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.
Note:
Your solution should is in logarithmic complexity.
Problem-Solving ideas: The focus is on the logarithmic time complexity, think of binary search, and just find a can.
1. If the array has only one number, then it is the peak.
2. If the array has only 2 digits, compare the large one to the peak.
3. If the array number is greater than 2, first determine the peak is not at the leftmost and most right end points, if not, then binary lookup, Mid = (start + end) >>1; if Num[mid] happens to be peak return, otherwise num[mid] will be the following conditions: A. On the downhill. B. On the uphill c. At the lowest point (can be seen as one of the preceding cases)
If it is downhill, then there must be a peak in the [Start,mid] interval because it is ascending at start and falling at mid. Other things in the same vein.
classSolution { Public: intFindpeak (vector<int> num,intStartintend) { intMid = (start + end) >>1; if(num[mid]>num[mid+1] && num[mid]>num[mid-1])returnmid; Else if(num[mid]>num[mid+1]) { returnFindpeak (Num,start,mid); } Else returnFindpeak (num,mid,end); } intFindpeakelement (Constvector<int> &num) { intLen =num.size (); if(len==1)return 0; if(num[0]>num[1])return 0; if(num[len-1]>num[len-2])returnlen-1; returnFindpeak (NUM,0, len-1); }};
Leetcode Find Peak Element