A peak element is an element that is strictly greater than its neighbors.
Given a 0-indexed 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] = -∞
. In other words, an element is always considered to be strictly greater than a neighbor that is outside the array.
You must write an algorithm that runs in O(log n)
time.
Example 1:
Input: nums = [1,2,3,1] Output: 2 Explanation: 3 is a peak element and your function should return the index number 2.
Example 2:
Input: nums = [1,2,1,3,5,6,4] Output: 5 Explanation: Your function can return either index number 1 where the peak element is 2, or index number 5 where the peak element is 6.
Constraints:
1 <= nums.length <= 1000
-231 <= nums[i] <= 231 - 1
nums[i] != nums[i + 1]
for all validi
.
注意:
1.明确一点,当middle不是峰值时,无论左边还是都应该会有一个峰值
2.这里用到了一个lambda表达式,用来处理边界的情况,因为这里要比左右两边都大,要处理刚好在最左边和最右边的情况
3.二分查找法:(1)当middle为峰值时,更新ret的值,并break,最后返回
(2)如果middle对应的值比middle+1对应的大,就往右,否则往左。
class Solution {
public:
int findPeakElement(vector<int>& nums) {
auto get=[&](int i)->pair<int,int>{
if(i==-1 || i==nums.size()){
return {0,0};
}
return {1,nums[i]};
};
int left=0;
int right=nums.size()-1;
int ret=-1;
while(left<=right){
int middle=left+(right-left)/2;
if(get(middle-1)<get(middle) && get(middle+1)<get(middle)){
ret=middle;
break;
}else if(get(middle)>get(middle-1)){
left=middle+1;
}else{
right=middle-1;
}
}
return ret;
}
};
标签:index,return,nums,int,Element,middle,element,Find,162
From: https://blog.csdn.net/2301_80161204/article/details/139577287