Find Peak Element —— Leetcode

本文介绍了一种使用二分查找法寻找数组中峰值元素的方法。峰值元素是指比其邻居大的元素。文章提供了一个C++实现的例子,该算法适用于没有重复元素的数组,并能够在O(log n)的时间复杂度内找到一个峰值的索引。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

A peak element is an element that is greater than its neighbors.

Given an input array where num[i] ≠ num[i+1], find a peak element and return its index.

The array may contain multiple peaks, in that case return the index to any one of the peaks is fine.

You may imagine that num[-1] = num[n] = -∞.

For example, in array [1, 2, 3, 1], 3 is a peak element and your function should return the index number 2.

二分法找峰值,代码中有一个注意点。

class Solution {
public:

    int binarySearch(vector<int> &nums, int low, int high) {
        if(low == high)
            return low;
            
        int mid1 = (low+high)/2;
        int mid2 = mid1+1;
        
        if(nums[mid1] < nums[mid2])
            return binarySearch(nums, mid2, high);  //此处若换成mid1则错误,应该选择高的。
        else
            return binarySearch(nums, low, mid1);
    }

    int findPeakElement(vector<int>& nums) {
        return binarySearch(nums, 0, nums.size()-1);
    }
};


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值