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

求解代码

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,这也就是我们要移除的窗口最左侧元素的下标。

相关推荐
Pniubi9 小时前
力扣283移动零(双指针法)
算法·leetcode·职场和发展
旖旎夜光19 小时前
LeetCode 315: 算右侧小于当前元素的个数(归并排序) —— 题解
c++·学习·算法·leetcode·排序算法
文丑颜不良啊20 小时前
LeetCode1401~1420题目解析
java·leetcode
Nuanyt20 小时前
LeetCode Hot 100 链表专题2 3 题 (Java)
java·笔记·算法·leetcode·链表
文丑颜不良啊20 小时前
LeetCode1341~1360题目解析
java·leetcode
海绵宝宝转agent20 小时前
LeetCodehot100题解
java·笔记·学习·算法·leetcode·深度优先
Pniubi1 天前
力扣543二叉树的直径(深度优先搜索法(递归))
算法·leetcode·职场和发展
j7~2 天前
【穷举、深搜与回溯算法】一棵决策树讲透全排列与子集
数据结构·c++·算法·leetcode·回溯·递归
Shaoshing2 天前
LeetCode100 42.接雨水
java·算法·leetcode
文丑颜不良啊2 天前
LeetCode1261~1280题目解析
java·leetcode