[Lintcode]Find Peak Element 寻找峰值

介绍了一种使用二分法在特定整数数组中查找峰值的方法,并提供了一个Java实现示例,该方法能在O(log n)的时间复杂度内找到至少一个峰值元素的位置。

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

There is an integer array which has the following features:

  • The numbers in adjacent positions are different.
  • A[0] < A[1] && A[A.length - 2] > A[A.length - 1].

We define a position P is a peek if:

A[P] > A[P-1] && A[P] > A[P+1]

Find a peak element in this array. Return the index of the peak.

Example

Given [1, 2, 1, 3, 4, 5, 7, 6]

Return index 1 (which is number 2) or 6 (which is number 7)

二分法查找,添加布尔型返回值,让查找到true时可以马上返回停止继续查找。、

class Solution {
    /**
     * @param A: An integers array.
     * @return: return any of peek positions.
     */
    public int findPeak(int[] A) {
        if(A.length < 3) return -1;
        
        int left = 0, right = A.length - 1;
        List<Integer> res = new ArrayList<Integer>();
        helper(A, left, right, res);
        
        return res.get(0);
    }
    
    boolean helper(int[] A, int left, int right, List<Integer> res) {
        if(left > right) return false;
        
        int mid = (left + right) / 2;
        if(mid - 1 >= 0 && mid + 1 <= A.length - 1 && A[mid - 1] < A[mid] &&
        A[mid + 1] < A[mid]) {res.add(mid); return true;};
        
        return helper(A, left, mid - 1, res) || helper(A, mid + 1, right, res);
        
        
    }
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值