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;
    }
}

全部评论

相关推荐

09-25 00:00
已编辑
电子科技大学 Java
球球与墩墩:这不是前端常考的对象扁平化吗,面试官像是前端出来的 const flattern = (obj) => { const res = {}; const dfs = (curr, path) => { if(typeof curr === 'object' && curr !== null) { const isArray = Array.isArray(curr); for(let key in curr) { const newPath = path ? isArray ? `${path}[${key}]` : `${path}.${key}` : key; dfs(curr[key], newPath); } } else { res[path] = curr } } dfs(obj); return res; }
查看3道真题和解析
点赞 评论 收藏
分享
10-02 19:29
已编辑
浙江科技大学 运营
点赞 评论 收藏
分享
昨天 16:33
已编辑
微软_sde(实习员工)
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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