LeetCode.239(剑指_59) 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.

For example,
Given nums = [1,3,-1,-3,5,3,6,7], and k = 3.

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

Therefore, return the max sliding window as [3,3,5,5,6,7].

Note:
You may assume k is always valid, ie: 1 ≤ k ≤ input array's size for non-empty array.

Follow up:
Could you solve it in linear time?

分析:

class Solution {
    public int[] maxSlidingWindow(int[] nums, int k) {
        //给定数组,和滑动窗口大小,每次滑动窗口只能滑动一个。
        //思路:使用暴力解法,那么每次需要查找k次,整个事件复杂度为O(nk)。更加巧妙的解法,使用双端队列Deque来实现
        //Deque可以在两头进行队列的操作,不过该队列存储的对应下标。用来保存可能是窗口最大的值的下标
       
        //精简版
        if(nums==null||nums.length==0||k>nums.length) return new int[0];
        
        int [] res=new int[nums.length-k+1];
        int count=0;
        //定义一个双端队列
        Deque<Integer> dq=new LinkedList<>();
        for(int i=0;i<nums.length;i++){
            
            //判断队列是否存在元素,且队列尾的元素不能小于当前处理元素
            while(!dq.isEmpty()&&nums[i]>=nums[dq.peekLast()]){
                //队尾出
                dq.pollLast();
            }
            
            //再判断对头元素下标是否过期了
            if(!dq.isEmpty()&&dq.peek()<i-k+1){
                //已经过期了,剔除
                dq.poll();
            }
            
            //添加当前处理元素
            dq.add(i);
            //取对头元素作为最大值放入结果集,使用队列的话,前面k-1的不进行赋值。例如3个元素,最大只有一个,那么2个是不需要赋值的
            if(i>=k-1){
                res[count++]=nums[dq.peek()];
            }   
        }
        return res;
        
       
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值