算法——山脉序列中的最大值

本文介绍了一种高效算法,用于在先增后减的山脉数组中查找最大值。通过二分搜索策略,我们可以在O(log n)的时间复杂度内找到山顶元素,避免了遍历整个数组的低效方式。

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

描述
给 n 个整数的山脉数组,即先增后减的序列,找到山顶(最大值)
您在真实的面试中是否遇到过这个题?
样例
例1:
输入: nums = [1, 2, 4, 8, 6, 3]
输出: 8
例2:
输入: nums = [10, 9, 8, 7],
输出: 10

实现:

public class Solution {
    /**
     * @param nums: a mountain sequence which increase firstly and then decrease
     * @return: then mountain top
     */
    public int mountainSequence(int[] nums) {
        // write your code here
        
          if (nums == null || nums.length == 0) {
            return -1;
        }

        int start = 0;
        int end = nums.length - 1;
        while (start + 1 < end) {
            int mid = start + (end - start) / 2;
            if (nums[mid] > nums[mid - 1]) {
                start = mid;
            }
            if (nums[mid] > nums[mid + 1]) {
                end = mid;
            }
        }
        return Math.max(nums[start], nums[end]);
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值