java 单调队列

滑动窗口的最大值

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

import java.util.*;
public class Solution {
    public ArrayList<Integer> maxInWindows(int [] num, int size){
        ArrayList<Integer> res = new ArrayList<>();
        if(size > num.length || size == 0){
            return res;
        }
        // 单调队列
        int j = 0;
        Deque<Integer>  queue = new ArrayDeque<>();
        // 初始化第一个窗口
        while(j < size){
            while(!queue.isEmpty() && num[j] > queue.peekLast()){
                queue.pollLast();
            }
            queue.addLast(num[j]);
            j++;
        }
        res.add(queue.peekFirst());
        // 以窗口右端index遍历一次
        while(j < num.length){
            // 如果上次窗口左端等于单调队列中最大的,要移除掉
            if(num[j-size] == queue.peekFirst()){
                queue.pollFirst();
            }
            // 新进来的值要更新队列维持其单调递减性
            while(!queue.isEmpty() && num[j] > queue.peekLast()){
                queue.pollLast();
            }
            // 将新值作为新窗口右端
            queue.addLast(num[j]);
            j++;
            // 添加每个窗口的最大值(单调队列的第一个元素)
            res.add(queue.peekFirst());
        }
        return res;
    }
}

全部评论

相关推荐

但听说转正率很低,我现在有在实习了,好纠结要不要去
熬夜脱发码农:转正率低归低,但是实习的经历你可以拿着,又不是说秋招不准备了
点赞 评论 收藏
分享
昨天 13:52
武汉大学 golang
点赞 评论 收藏
分享
点赞 评论 收藏
分享
ohs的小木屋:比不少实习待遇高了
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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