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

滑动窗口的最大值

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

public class Solution {
    public ArrayList<Integer> maxInWindows(int [] num, int size) {
        if(size==0||size>num.length||num==null) return null;
        ArrayList<Integer> res=new ArrayList<>();
        //LinkedList继承了Deque接口,可当做Deque使用
        LinkedList<Integer> queue=new LinkedList<>();
        for(int i=0;i<num.length;i++){
            //把这个数之前比它小的剔除出去,比它大的留下,到时候大的会先被放出去
            while(!queue.isEmpty()&&num[queue.peekLast()]<num[i]){
                queue.removeLast();
            }
            queue.offerLast(i);
            //获取左边界的index
            int l=i-size+1;
            //判断当前最大值是否在滑动窗口外,如果是,移除
            if(l>queue.peekFirst()) queue.removeFirst();
            //l是否大于等于0,即左边界是否是第一个数开始
            if(i+1>=size) res.add(num[queue.peekFirst()]);
        }
        return res;
    }
}
全部评论

相关推荐

陆续:不可思议 竟然没那就话 那就我来吧 :你是我在牛客见到的最美的女孩
点赞 评论 收藏
分享
不愿透露姓名的神秘牛友
昨天 12:04
毕业生招你惹你了,问一个发薪日来一句别看网上乱七八糟的你看哪个工作没有固定发薪日扭头就取消了面试就问了一句公司都是这个态度吗还搞上人身攻击了...
程序员小白条:呃呃呃,都还没面试,我都不会问这么细,何况通不通过,去不去都另说,你没实力和学历的话,在外面就这样,说实话没直接已读不回就不错了,浪费时间基本上
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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