Title:
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.
idea: This problem if you do not use binary search, time complexity is O (N), we need to iterate through the array, find the first element, it is larger than its subsequent other elements, is the local peak. In the title, we consider using binary search to complete the search within a logarithmic time. If the intermediate element is greater than its adjacent successive elements, the left side of the intermediate element (including the middle element) necessarily contains a local maximum value, and if the intermediate element is less than its adjacent successive elements, the right side of the intermediate element must contain a local maximum. Until the last left edge meets the right edge, we find the peak we are seeking.
We select the left and right edges to meet as the end condition, and only compare with the subsequent element mid+1, you can avoid considering that when mid is 0 o'clock, mid-1 is a negative value for the special case. The question is just let's assume num[-1] = num[n] = Negative infinity, in fact, the array is not able to get these two values, the pointer will be out of bounds.
Here, we also need to note that when the middle element is greater than its adjacent successive elements, the left side of the middle element (including the intermediate element) must contain a local maximum value, then the middle element may also be a peak point, so when moving, end = Mid, but not across the intermediate element end = Mid-1. In the opposite case, the middle element is less than its adjacent successive elements, and the right side of the middle element contains a local maximum, when the middle element must not be the local maximum point, and start = mid + 1.
Complexity: O (LG (N))
AC Code:
Class Solution {public: int findpeakelement (const vector<int> &num) { if (num.size () = = 0) return 0;
int start = 0; int end = Num.size ()-1; while (start <= end) { if (start = = end) return start; int mid = start + (End-start)/2; if (Num[mid] < num[mid+1]) { start = mid + 1; } else { end = mid;}}} ;
After the completion of the two points to find all the questions, you can summarize the characteristics of this type of problem, as well as all the application of binary search.
[C + +] leetcode:118 Find peak Element (binary lookup finds array local peaks)