博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
剑指offer(66):滑动窗口的最大值
阅读量:4286 次
发布时间:2019-05-27

本文共 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]}。

分析

用一个双端队列存储可能为最大值的索引,队列第一个位置保存当前窗口的最大值,当窗口滑动一次:

  1. 判断当前最大值是否过期
  2. 新增加的值从队尾开始比较,把所有比他小的值丢掉

牛客AC:

public class MaxInWindows {
public ArrayList
maxInWindows(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/

你可能感兴趣的文章
测试大牛的博客地址
查看>>
Tomcat6.0的安装与配置
查看>>
测试套件edit里的名称含义
查看>>
工作区Run
查看>>
PyCharm找不到自己安装的module ImportError: No module named 。。。
查看>>
python的ConfigParser模块
查看>>
Python+Selenium中级篇之5-Python读取配置文件内容
查看>>
Python+Selenium练习篇之27-多窗口之间切换----修改后的
查看>>
Python+Selenium中级篇之2-Python中类/函数/模块的简单介绍和方法调用------修改后的
查看>>
Python+Selenium中级篇之7-Python中字符串切割操作--修改
查看>>
Python+Selenium中级篇之8-Python自定义封装一个简单的Log类---修改
查看>>
logging.getLogger(logger)
查看>>
os.path.dirname(__file__)使用---获取当前运行脚本的绝对路径
查看>>
error: cannot connect to daemon(adb.exe start-server' failed启动失败,端口占用)---关闭360手机助手即可
查看>>
Python+Selenium框架设计篇之4-框架内封装日志类和浏览器引擎类
查看>>
Python+Selenium框架设计篇之11-自动化测试报告的生成-修改
查看>>
Android Studio中连接真机查看log
查看>>
文件上传功能测试用例
查看>>
测试qq发送文件
查看>>
Sql语句: 取出表A中第31到第40记录
查看>>