本文共 1334 字,大约阅读时间需要 4 分钟。
题目描述
给定一个数组和滑动窗口的大小,找出所有滑动窗口里数值的最大值。例如,如果输入数组{2,3,4,2,6,2,5,1}及滑动窗口的大小3,那么一共存在6个滑动窗口,他们的最大值分别为{4,4,6,6,6,5};针对数组{2,3,4,2,6,2,5,1}的滑动窗口有以下6个: {[2,3,4],2,6,2,5,1}, {2,[3,4,2],6,2,5,1}, {2,3,[4,2,6],2,5,1}, {2,3,4,[2,6,2],5,1}, {2,3,4,2,[6,2,5],1}, {2,3,4,2,6,[2,5,1]}。
分析
用一个双端队列存储可能为最大值的索引,队列第一个位置保存当前窗口的最大值,当窗口滑动一次:
牛客AC:
public class MaxInWindows { public ArrayListmaxInWindows(int[] num, int size) { ArrayList maxList = new ArrayList<>(); if (size == 0) return maxList; int begin; // 窗口所在第一个元素的索引 Deque indexDeque = new ArrayDeque<>(); for (int i = 0; i < num.length; i++) { begin = i - size + 1; if (indexDeque.isEmpty()) indexDeque.add(i); // 1、deque中元素的索引小于begin,即该元素已经在窗口外(过期),丢掉 else if (begin > indexDeque.peekFirst()) indexDeque.pollFirst(); // 2、新增加的值从队尾开始比较,把所有比他小的值丢掉 while ((!indexDeque.isEmpty()) && num[i] >= num[indexDeque.peekLast()]) indexDeque.pollLast(); indexDeque.add(i); if (begin >= 0) // 窗口的第一个元素索引大于0 maxList.add(num[indexDeque.peekFirst()]); } return maxList; }}
参考
1. 何海涛,剑指offer名企面试官精讲典型编程题(纪念版),电子工业出版社转载地址:http://lkxgi.baihongyu.com/