Find Peak Element, findpeakelement
A peak element is an element that is greater than its neighbors.
Given an input array wherenum[i] ≠ num[i+1]
, Find a peak element and return its index.
The array may contain in multiple peaks, in that case return the index to any one of the peaks is fine.
You may imagine thatnum[-1] = num[n] = -∞
.
For example, in array[1, 2, 3, 1]
, 3 is a peak element and your function shocould return the index number 2.
Algorithm 1: half-Lookup
If the right neighbor of the intermediate point is smaller than the intermediate point, the right interval can be excluded. Because a peak must exist from the center point to the left.
If the left neighbor of the intermediate vertex is smaller than the intermediate vertex, the left interval can be excluded. Because a peak must exist from the center point to the right.
Note that when there are only two elements in the interval, the left endpoint and the center point are the same endpoint. Special processing is required.
class Solution {public: int findPeakElement(vector<int>& nums) { int left = 0; int right = nums.size()-1; while (left < right) { const int mid = left + (right - left) / 2; if (nums[mid+1] < nums[mid]) right = mid; else if (left != mid) left = mid; else return nums[left] > nums[right] ? left : right; } return left; }};
The problem above is that when left and mid are equal, there will be an endless loop without special processing.
The condition can be improved. When the right neighbor of the intermediate point is greater than the center point, the left interval and the center point are discarded. That is, it is discarded along with the intermediate point.
class Solution {public: int findPeakElement(vector<int>& nums) { int left = 0; int right = nums.size()-1; while (left < right) { const int mid = left + (right - left) / 2; if (nums[mid+1] > nums[mid]) left = mid+1; else right = mid; } return left; }};
Algorithm 2: sequential search
Find the first element, which is greater than its right neighbor.
That is, find the right boundary that meets the ascending order.
class Solution {public: int findPeakElement(vector<int>& nums) { int peak = 0; const int bound = nums.size()-1; while (peak < bound && nums[peak] < nums[peak+1]) ++peak; return peak; }};
This algorithm is O (n). Although it is not as good as algorithm 1, it is also an idea. In leetcode, the running time is no longer than that of the previous algorithm.