题目链接:https://leetcode.com/problems/find-peak-element/
A peak element is an element that is greater than its neighbors.
Given an input array where num[i] ≠ num[i+1]
, find a peak element and return its index.
The array may contain multiple peaks, in that case return the index to any one of the peaks is fine.
You may imagine that 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.
思路:二分查找, 如果找到一个nums[mid] > nums[mid+1], 那么可以保证在[left, mid]区间必然存在至少一个peak, 因为每个相邻的值都不同并且最左边是负无穷, 所以如果nums[mid-1]<nums[mid]那么nums[mid]就是一个peak. 否则如果nums[mid-1] > nums[mid]那么又回到上面的问题.
代码如下:
class Solution {
public:
int findPeakElement(vector<int>& nums) {
int left = 0, right = nums.size()-1;
while(left < right)
{
int mid = (left+right)/2;
if(nums[mid] > nums[mid+1]) right = mid;
else left = mid+1;
}
return left;
}
};