您现在的位置是:首页 > 文章详情

[剑指offer] 滑动窗口的最大值

日期:2018-07-24点击:408

本文首发于我的个人博客:[尾尾部落](https://weiweiblog.cn/maxinwindows/

题目描述

给定一个数组和滑动窗口的大小,找出所有滑动窗口里数值的最大值。例如,如果输入数组{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]}。

解题思路

法一:简单的暴力法
法二:双向队列
用一个双向队列,队列第一个位置保存当前窗口的最大值,当窗口滑动一次,判断当前最大值是否过期(当前最大值的位置是不是在窗口之外),新增加的值从队尾开始比较,把所有比他小的值丢掉。这样时间复杂度为O(n)。

参考代码

法一:简单的暴力法

import java.util.ArrayList; public class Solution { public ArrayList<Integer> maxInWindows(int [] num, int size) { ArrayList<Integer> res = new ArrayList<Integer>(); if(num.length < size || size == 0) return res; for(int i = 0; i < num.length - size + 1; i++){ res.add(max(num, i, size)); } return res; } public int max(int [] num, int index, int size){ int res = num[index]; for(int i = index + 1; i < index + size; i++){ if(num[i] > res) res = num[i]; } return res; } } 

法二:双向队列

import java.util.ArrayList; import java.util.LinkedList; public class Solution { public ArrayList<Integer> maxInWindows(int [] num, int size){ ArrayList<Integer> res = new ArrayList<Integer>(); LinkedList<Integer> deque = new LinkedList<Integer>(); if(num.length == 0 || size == 0) return res; for(int i = 0; i < num.length; i++){ if(!deque.isEmpty() && deque.peekFirst() <= i - size) deque.poll(); while(!deque.isEmpty() && num[deque.peekLast()] < num[i]) deque.removeLast(); deque.offerLast(i); if(i + 1 >= size) res.add(num[deque.peekFirst()]); } return res; } } 
原文链接:https://yq.aliyun.com/articles/642766
关注公众号

低调大师中文资讯倾力打造互联网数据资讯、行业资源、电子商务、移动互联网、网络营销平台。

持续更新报道IT业界、互联网、市场资讯、驱动更新,是最及时权威的产业资讯及硬件资讯报道平台。

转载内容版权归作者及来源网站所有,本站原创内容转载请注明来源。

文章评论

共有0条评论来说两句吧...

文章二维码

扫描即可查看该文章

点击排行

推荐阅读

最新文章