剑指offer59.Ⅰ滑动窗口的最大值。简单易懂注释版0ms

本文介绍了一种求解滑动窗口中最大值的高效算法。通过使用双端队列来跟踪当前窗口内的元素,该算法能够在O(n)的时间复杂度内完成计算。具体实现上,我们维护了一个双端队列,用来保存窗口内的元素下标,并确保队列头部始终为当前窗口的最大值。

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

class Solution {
    public int[] maxSlidingWindow(int[] nums, int k) {
        if(nums == null || nums.length == 0) return new int[0];
        int[] result = new int[nums.length - k + 1];
        Deque<Integer> queue = new ArrayDeque();
        // i:记录nums j:记录result
        for(int i = 0, j = 0; i < nums.length; i++){
            // poll():查看后删除 pop():只查看不删除
            // 数量大于滑动窗口大小,去掉多余的
            if(!queue.isEmpty() && i - queue.peek() >= k) queue.poll();
            // 找到最大值,注意得是peekLast和poolLast,nums[i]>后面的
            while(!queue.isEmpty() && nums[i] > nums[queue.peekLast()]) queue.pollLast();
            queue.add(i);
            if(i >= k - 1) result[j++] = nums[queue.peek()];
        }
        return result;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值