leetcode 162. Find Peak Element

题目描述

如果nums[i-1]<nums[i]并且nums[i]>nums[i+1],那么nums[i]就是峰值。除此情况之外,nums[i-1]和nums[i+1]至少有一个大于nums[i],因为题目已经保证相邻的元素不相等。坚持向上坡方向走一定能达到一个峰值,如果往两边走都是上坡,那就随意向两边选一个方向走。

cpp 复制代码
class Solution {
public:
    int findPeakElement(vector<int>& nums) {
        int left = 0;
        int right = nums.size() -1;
        int mid = 0;
        while(left<=right){
            mid = (left+right)/2;
            if(greater_left(nums,mid) && greater_right(nums,mid))
                return mid;
            if(greater_left(nums,mid)){
                //往左走是下坡,所以应该向右走
                left = mid +1;
            }else{
                //往左走是上坡,所以应该向左走
                //这里包含了,往左往右都是上坡的情况,此时选择往左走
                right = mid -1;
            }
        }
        return left;
    }

    //nums[idx]是否比它左边的元素大
    bool greater_left(vector<int>& nums,int idx){
        if(idx == 0)
            return true;
        return nums[idx]>nums[idx-1];
    }
    //nums[idx]是否比它右边的元素大
    bool greater_right(vector<int>& nums,int idx){
        if(idx == nums.size() -1)
            return true;
        return nums[idx]>nums[idx+1];
    }
};
相关推荐
小白程序员成长日记8 分钟前
2025.11.08 力扣每日一题
算法·leetcode·职场和发展
他们叫我一代大侠2 小时前
Leetcode :模拟足球赛小组各种比分的出线状况
算法·leetcode·职场和发展
海琴烟Sunshine2 小时前
leetcode 345. 反转字符串中的元音字母 python
python·算法·leetcode
一只鱼^_6 小时前
力扣第 474 场周赛
数据结构·算法·leetcode·贪心算法·逻辑回归·深度优先·启发式算法
夏鹏今天学习了吗9 小时前
【LeetCode热题100(64/100)】搜索旋转排序数组
算法·leetcode·职场和发展
alphaTao9 小时前
LeetCode 每日一题 2025/11/3-2025/11/9
windows·leetcode
小安同学iter1 天前
SQL50+Hot100系列(11.7)
java·算法·leetcode·hot100·sql50
谈笑也风生1 天前
只出现一次的数字 II(一)
数据结构·算法·leetcode
aloha_7891 天前
测试开发工程师面经准备(sxf)
java·python·leetcode·压力测试
im_AMBER1 天前
Leetcode 47
数据结构·c++·笔记·学习·算法·leetcode