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 小时前
Leetcode hot100 每日温度【中等】
算法·leetcode·职场和发展
样例过了就是过了1 小时前
LeetCode热题100 分割等和子集
数据结构·c++·算法·leetcode·动态规划
麦兜和小可的舅舅2 小时前
ClickHouse 列管理机制解析:从 COW、IColumn 到 CRTP
c++·clickhouse
北顾笙9802 小时前
day38-数据结构力扣
数据结构·算法·leetcode
m0_629494732 小时前
LeetCode 热题 100-----14.合并区间
数据结构·算法·leetcode
xin_nai2 小时前
LeetCode热题100(Java)(5)普通数组
算法·leetcode·职场和发展
旖-旎2 小时前
深搜练习(组合)(5)
c++·算法·深度优先·力扣
vegetablesssss2 小时前
vtk镜像图
c++·qt·vtk
@小码农3 小时前
2026年3月Scratch图形化编程等级考试一级真题试卷
开发语言·数据结构·c++·算法
【 】4233 小时前
C++&STL(Standard Template Library,标准模板库)
java·开发语言·c++