C++ | Leetcode C++题解之第162题寻找峰值

题目:

题解:

cpp 复制代码
class Solution {
public:
    int findPeakElement(vector<int>& nums) {
        int n = nums.size();

        // 辅助函数,输入下标 i,返回一个二元组 (0/1, nums[i])
        // 方便处理 nums[-1] 以及 nums[n] 的边界情况
        auto get = [&](int i) -> pair<int, int> {
            if (i == -1 || i == n) {
                return {0, 0};
            }
            return {1, nums[i]};
        };

        int left = 0, right = n - 1, ans = -1;
        while (left <= right) {
            int mid = (left + right) / 2;
            if (get(mid - 1) < get(mid) && get(mid) > get(mid + 1)) {
                ans = mid;
                break;
            }
            if (get(mid) < get(mid + 1)) {
                left = mid + 1;
            }
            else {
                right = mid - 1;
            }
        }
        return ans;
    }
};
相关推荐
钓鱼的肝1 天前
梳理(1-5)
c++·经验分享·笔记·算法·青少年编程
参.商.1 天前
【Day 53】76. 最小覆盖子串
leetcode·golang
jimy11 天前
readelf 查看“派生类”的vtable符号
开发语言·c++
蒸蒸yyyyzwd1 天前
cpp 选手秋招学习笔记 day37 面经学习
c++·八股
YYYing.1 天前
【C++进阶系列 (七)】C++ RTTI 深度剖析:从 typeid 到 dynamic_cast 的底层之旅
开发语言·c++·c/c++·rtti
虚无的纽扣1 天前
【力扣刷题】第二天:无重复字符的最长字串、移动零问题
算法·leetcode·排序算法
钓鱼的肝1 天前
csp-j-s总结(2)
c++·经验分享·笔记·算法·青少年编程
重生的黑客1 天前
Qt 常用控件精讲(1):QWidget 核心属性全解 —— 从 geometry 到 qrc 与 QSS
c++·qt·qwidget·qss·常用控件
Hespethorn1 天前
取 `X-Forwarded-For` 首段做频控 key,等于把限流开关交给了调用方
c++
米糕闯编程1 天前
鱼香ros2(七)功能包组织C++节点
c++·ros2·cmakelists