题解 | #滑动窗口的最大值#

滑动窗口的最大值

http://www.nowcoder.com/practice/1624bc35a45c42c0bc17d17fa0cba788

单调队列

import java.util.*;
public class Solution {
    public ArrayList<Integer> maxInWindows(int [] num, int size) {
        //使用一个大小为size的双端队列保存最大值,维持队首元素为最大值,当窗口滑动的时候,删除小于等于当前划出窗口的元素
        ArrayDeque<Integer> max = new ArrayDeque<>();
        ArrayList<Integer> res = new ArrayList<>();
        int len = num.length;
        if(len==0 || len < size || size < 1) return res;
        for(int i = 0;i < len;i++){
           while(!max.isEmpty() && num[max.peekLast()]<num[i]){
               max.pollLast();
           }
            max.addLast(i);
            //判断队列的头部元素是否过期
            if(max.peekFirst()+size <= i){
                max.pollFirst();
            }
            //判断是否形成了窗口
            if(i+1>=size){
                res.add(num[max.peekFirst()]);
            }
        }
        
        return res;
        
    }
}
全部评论

相关推荐

12-15 14:16
门头沟学院 Java
回家当保安:发offer的时候会背调学信网,最好不要这样。 “27届 ”和“28届以下 ”公司招聘的预期是不一样的。
实习简历求拷打
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务