leetcode----162. Find Peak Element

本文介绍了一种使用二分查找算法来高效寻找数组中峰顶元素的方法。峰顶元素定义为大于其左右相邻元素的值,文章详细解释了如何将二分查找应用于此问题,以达到对数时间复杂度。

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

链接:

https://leetcode.com/problems/find-peak-element/

大意:

返回一个数组的峰顶值所在的位置。一个数组的峰顶值:该值大于其左右两边相邻的两个元素。规定:nums[0]左边和nums[nums.length - 1]右边可以认为是Integer.MIN_VALUE。例子:

思路:

顺序遍历,找到第一个降序的点即可。

代码:

class Solution {
    public int findPeakElement(int[] nums) {
        if (nums.length <= 1)
            return 0;
        int i = 0;
        // 找到第一个降序的点
        while (i + 1 < nums.length && nums[i] < nums[i + 1]) {
            i++;
        }
        return i == nums.length ? i - 1 : i;
    }
}

结果:

结论:

刚才又认真地看了遍题目,说是最好用对数复杂度解决,自己的方法是线性复杂度,有待改进。

最佳:(基于二分查找)

class Solution {
    public int findPeakElement(int[] nums) {
        //easy solution is O(n) 
        //How to use binary search
        int l = 0, r = nums.length-1;
        while ( l < r ) {
            //System.out.println(l + " " + r);
            int m = (l+r)/2;
            int m1 = m+1;
            int m2 = m > 0 ? m-1 : m;
            //Find the target that bigger that its neighbor
            if ( nums[m] > nums[m1] && nums[m] >= nums[m2] ) {
                return m;
            } else if ( nums[m] > nums[m1] ) {
                r = m;
            } 
            // Actually can go either ways if both nums[m] lesser than both its neighbor. For the sake of simplicity, we go right so we don't need to check for other condition. 
            else  
                l = m1;
        }
        //since we check with m+1, need to return l
        return l;
    }
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值