#leetcode#Find Peak Element

本文介绍如何利用二分查找算法解决找峰元素问题。通过比较相邻元素的大小,快速定位到峰值元素所在的位置。算法具有O(log n)的时间复杂度,适用于大型数据集。

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

Find Peak Element

  Total Accepted: 31990  Total Submissions: 101250 My Submissions
Question Solution 

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.

click to show spoilers.

Note:

Your solution should be in logarithmic complexity.

-----------------------------------------------------------------------------------------------------------------------------

知道用binary search,但是一开始思路局限在nums[mid]要和nums[mid - 1], nums[mid + 1] 做比较来看nums[mid] 是否是 peak,这题只要返回任意一个peak就可以了, 这题给出条件 num[i] != num[i + 1], 算是个提示吧, 每次二分只要比较 nums[mid] 和 nums[mid + 1] 的大小关系就可以了

while(l < r){}, 最后返回 l 或者 r 都是可以的,因为while循环结束后 l == r

public class Solution {
    public int findPeakElement(int[] nums) {
        if(nums == null || nums.length == 0)
            return -1;
        int l = 0;
        int r = nums.length - 1;
        while(l < r){
            int mid = l + (r - l) / 2;
            if(nums[mid] > nums[mid + 1]){
                r = mid;
            }else{//nums[mid] < nums[mid + 1]
                l = mid + 1;
            }
        }
        return r;
    }
}

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值