LeetCode 162. Find Peak Element
A peak element is an element that is strictly greater than its neighbors.
Given an integer array nums
, find a peak
element, and return its index. If the array contains multiple peaks, return the index to any of the peaks.
You may imagine that nums[-1] = nums[n] = -∞
.
You must write an algorithm that runs in $O(logn)$ time.
示例 1:
输入:nums = [1,2,3,1]
输出:2
解释:3 是峰值元素,你的函数应该返回其索引 2。
示例 2:
输入:nums = [1,2,1,3,5,6,4]
输出:1 或 5
解释:你的函数可以返回索引 1,其峰值元素为 2;
或者返回索引 5, 其峰值元素为 6。
method: 二分模板一
如果mid
比mid+1
大,说明峰值在左边,所以r=mid
如果mid
比mid+1
小,说明峰值在右边,所以l=mid+1
考虑边界条件,l
指向倒数第二个元素,r
指向最后一个元素,mid
是l
如果满足条件,则r = mid = l
,退出,结果正确
如果不满足,则l = mid + 1 = r
,退出,结果也正确
int findPeakElement(vector<int>& nums) {
int l = 0, r = nums.size() - 1;
while (l < r) {
int mid = l + r >> 1;
if (nums[mid] > nums[mid + 1]) r = mid;
else l = mid + 1;
}
return r;
}
时间复杂度:$O(logn)$
空间复杂度:$O(1)$
模板二
模板二是上取整,所以和mid-1
比较不会越界
int findPeakElement(vector<int>& nums) {
int l = 0, r = nums.size() - 1;
while (l < r) {
int mid = l + r + 1 >> 1;
if (nums[mid] > nums[mid - 1]) l = mid;
else r = mid - 1;
}
return l;
}