162. 寻找峰值
峰值元素是指其值大于左右相邻值的元素。
给定一个输入数组 nums,其中 nums[i] ≠ nums[i+1],找到峰值元素并返回其索引。
数组可能包含多个峰值,在这种情况下,返回任何一个峰值所在位置即可。
你可以假设 nums[-1] = nums[n] = -∞。
Example 1
输入: nums = [1,2,3,1]
输出: 2
解释: 3 是峰值元素,你的函数应该返回其索引 2。
Example 2
输入: nums = [1,2,1,3,5,6,4]
输出: 1 或 5
解释: 你的函数可以返回索引 1,其峰值元素为 2;
或者返回索引 5, 其峰值元素为 6。
二分查找
这道题参考了评论区的思路写的,只要nums[mid]<nums[mid+1],就会向右折半查找,一旦low == high时,它们一定会指向一个峰值
static const auto io_speed_up = []()
{
std::ios::sync_with_stdio(false);
cin.tie(nullptr);
return 0;
}();
class Solution {
public:
int findPeakElement(vector<int>& nums) {
if(nums.size() == 1)
{
return 0;
}
int low = 0;
int high = nums.size()-1;
while(low<high)
{
int mid = low+(high-low)/2;
if(nums[mid]<nums[mid+1]) low = mid+1;
else high = mid;
}
return low;
}
};