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;
    }
};
相关推荐
渡我白衣37 分钟前
C++ 同名全局变量:当符号在链接器中“相遇”
开发语言·c++·人工智能·深度学习·microsoft·语言模型·人机交互
Emilia486.1 小时前
【Leetcode&nowcode】代码强化练习(二叉树)
算法·leetcode·职场和发展
墨染点香1 小时前
LeetCode 刷题【135. 分发糖果】
算法·leetcode·职场和发展
是那盏灯塔2 小时前
【算法】——动态规划之01背包问题
数据结构·c++·算法·动态规划
im_AMBER2 小时前
Leetcode 41
笔记·学习·算法·leetcode
迷失的walker3 小时前
【Qt C++ QSerialPort】QSerialPort fQSerialPortInfo::availablePorts() 执行报错问题解决方案
数据库·c++·qt
Excuse_lighttime3 小时前
排序数组(快速排序算法)
java·数据结构·算法·leetcode·eclipse·排序算法
南方的狮子先生4 小时前
【数据结构】(C++数据结构)查找算法与排序算法详解
数据结构·c++·学习·算法·排序算法·1024程序员节
紫荆鱼4 小时前
设计模式-适配器模式(Adapter)
c++·设计模式·适配器模式
前进的李工4 小时前
LeetCode hot100:560 和为k的子数组:快速统计法
python·算法·leetcode·前缀和·哈希表