【单调队列】滑动窗口的最大值

求解代码

java 复制代码
class MonotonicQueue {
        LinkedList<Integer> queue = new LinkedList<>();
        public void push(int n){
            while(!queue.isEmpty()&&queue.getLast()<n){
                queue.pollLast();
            }
            queue.addLast(n);
        }

        public void pop(int n){
            if(n==queue.getFirst()){
                queue.pollFirst();
            }
        }

        public int max(){
            return queue.getFirst();
        }

    }
    public ArrayList<Integer> maxInWindows (int[] num, int size) {

        MonotonicQueue window = new MonotonicQueue();

        ArrayList<Integer> res = new ArrayList<>();        
        if(num==null||size<=0||num.length==0||size>num.length){
            return res;
        }


        for(int i=0;i<num.length;i++){
            if(i<size-1){
                window.push(num[i]);
            }else{
                window.push(num[i]);
                res.add(window.max());
                window.pop(num[i-size+1]);
            }
        }
        return res;
    }

小贴士

1.构建一个特殊的【单调队列】来充当不断滑动的窗口

这个单调队列的队首 记录了滑动过程中的最大值(对应max方法),从队首到队尾 的元素值大小是单调递减的;

队列为空或者尾部的元素(getLast)小于要入队的元素时,将该尾部元素弹出(pollLast),元素是从队列尾部入队的(addLast)。

滑动窗口需要移除的元素等于队列头部(当前最大值)时,将队首元素弹出(pollFirst);

2.解释一下这个i-size+1

对于长度固定为size的滑动窗口,当窗口还没填满时,不考虑计算最大值和移除元素,直到把前size-1个元素填满;

从第size个元素开始(对应就是下标size-1),窗口正式填满,此时,依次完成把当前元素加入窗口,将窗口的最大值记录到res中,再把窗口最左侧的元素移除,为下一步滑动腾出一个位置。

那窗口最左侧元素的下标是什么呢?

因为当前元素是num[i],所以此时的窗口的右边界是i,又因为窗口的大小固定为size,所以,窗口的左边界就是i-size+1,这也就是我们要移除的窗口最左侧元素的下标

相关推荐
玄昌盛不会编程2 小时前
LeetCode——2091. 从数组中移除最大值和最小值
java·算法·leetcode
旖旎夜光3 小时前
LeetCode 238:除自身以外数组的乘积(前缀和) —— 题解
数据结构·c++·算法·leetcode·前缀和
学习星球16 小时前
单调栈——从“找下一个更大的“到柱状图中的最大矩形
数据库·c++·算法·leetcode·xcode
血小板要健康19 小时前
网格 dfs 与 FloodFill:从岛屿、区域到搜索路径
笔记·算法·leetcode·深度优先
鹿角片ljp1 天前
LeetCode 141. 环形链表|从 HashSet 到快慢指针 O (1) 空间最优解
算法·leetcode·链表
ZC跨境爬虫1 天前
LeetCode 219. 存在重复元素 II(滑动窗口 + 哈希表详解)
算法·leetcode·散列表
Navigator_Z1 天前
LeetCode //C - 1220. Count Vowels Permutation
c语言·算法·leetcode
feilieren1 天前
leetcode - 389. 找不同
算法·leetcode
evans在进步1 天前
LeetCode 238 除自身以外数组的乘积:前缀积与后缀积详解
算法·leetcode·职场和发展
刃神太酷啦2 天前
Linux 系统 MySQL 完整安装配置教程:从卸载 MariaDB 到优化 my.cnf----《Hello MySQL!》(1)
android·linux·c语言·c++·mysql·leetcode·mariadb