leetcode 239. Sliding Window Maximum(滑动窗口最大值)

本文介绍了一种解决滑动窗口最大值问题的高效算法,通过使用单调队列实现线性时间复杂度,避免了在每个窗口位置重复查找最大值的低效操作。算法详细解释了如何维护队列,确保队首始终是当前窗口的最大值。

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

Given an array nums, there is a sliding window of size k which is moving from the very left of the array to the very right. You can only see the k numbers in the window. Each time the sliding window moves right by one position. Return the max sliding window.

Follow up:
Could you solve it in linear time?

Example:

Input: nums = [1,3,-1,-3,5,3,6,7], and k = 3
Output: [3,3,5,5,6,7]
Explanation:

Window position                Max
---------------               -----
[1  3  -1] -3  5  3  6  7       3
 1 [3  -1  -3] 5  3  6  7       3
 1  3 [-1  -3  5] 3  6  7       5
 1  3  -1 [-3  5  3] 6  7       5
 1  3  -1  -3 [5  3  6] 7       6
 1  3  -1  -3  5 [3  6  7]      7

Constraints:

1 <= nums.length <= 10^5
-10^4 <= nums[i] <= 10^4
1 <= k <= nums.length

给出一个数组和size为k的滑动窗口,每次滑动窗口向右移动一位,输出每次移动中滑动窗口中的最大值。

假设数组长度为n,那么一共输出n-k+1个窗口最大值。

思路:
最简单粗暴的方法是每移动一位就在滑动窗口内搜索最大值。
此处参考一个方法,用一个单调储存元素的队列,最大值在队列的head,而且每次添加元素时把小于新元素的全部删掉,那么每次输出仅需要输出队列的head元素。

注意队列中可以储存重复的元素,因为假如窗口右移时左边元素出了窗口,就需要把左边的元素移除队列,这时如果左边元素是最大值,相当于最大值移除队列,但是如果窗口中仍有同样的最大值元素,就应该有重复的元素仍然在队列中。

java中用到deque结构,用到ArrayDeque, 其中getFirst和offerFirst的区别是如果队列中没有元素,那么getFirst会抛出Exception, 但是offerFirst不会抛出异常,会直接返回null, 同样的还有pollFirst(不抛出异常)和removeFirst(会抛出异常)。

class Solution {
    public int[] maxSlidingWindow(int[] nums, int k) {
        monoQueue queue = new monoQueue();
        int n = nums.length;
        int[] result = new int[n - k + 1];
        
        for(int i = 0; i < nums.length; i++) {
            queue.push(nums[i]);
            if(i >= k && nums[i - k] == queue.getMax()) {
                queue.pop();
            }
            if(i + 1 >= k) {
                result[i - k + 1] = queue.getMax();
            }
        }
        
        return result;
    }
}

class monoQueue{
    private Deque<Integer> deque = new ArrayDeque<>();
    
    //add element and delete all elements smaller than it
    public void push(int num) {
        while(!deque.isEmpty() && num > deque.peekLast()) {
            deque.pollLast();
        }
        
        deque.offerLast(num);
    }
    
    //delete the head(max element)
    public void pop(){
        deque.pollFirst();
    }
    
    //return the head(max element)
    public int getMax(){
        return deque.peekFirst();
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

蓝羽飞鸟

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值