博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Sliding Window Maximum
阅读量:4567 次
发布时间:2019-06-08

本文共 1525 字,大约阅读时间需要 5 分钟。

问题描述

Given an array nums, there is a sliding window of size k which is moving from the very left of the array to the very right. You can only see the k numbers in the window. Each time the sliding window moves right by one position.

For example,

Given nums = [1,3,-1,-3,5,3,6,7], and k = 3.

Window position                Max---------------               -----[1  3  -1] -3  5  3  6  7       3 1 [3  -1  -3] 5  3  6  7       3 1  3 [-1  -3  5] 3  6  7       5 1  3  -1 [-3  5  3] 6  7       5 1  3  -1  -3 [5  3  6] 7       6 1  3  -1  -3  5 [3  6  7]      7

Therefore, return the max sliding window as [3,3,5,5,6,7].

 

解决思路

1. 最直观的方法就是逐个比较,时间复杂度为O(kn);

2. 另一种更加巧妙的方法是借助一个双向队列,滑窗的同时记录下当前窗口的最大值。

具体做法为

1. 输入元素的个数不足k时,进队列;

2. 否则,比较当前元素和队列尾部的元素,如果队列尾部的元素小于当前元素则不断地将队尾元素出队;

3. 每次记录下队列的头元素为滑动窗口中的最大元素,并且需要判断该最大元素是否为窗口的首元素,如果是则需要移除。

 

程序

public class Solution {    public int[] maxSlidingWindow(int[] nums, int k) {		if (nums == null || nums.length == 0 || nums.length < k) {			return new int[0];		}		LinkedList
doublyQueue = new LinkedList
(); int[] maxs = new int[nums.length - k + 1]; for (int i = 0; i < nums.length; i++) { while (!doublyQueue.isEmpty() && doublyQueue.getLast() < nums[i]) { doublyQueue.removeLast(); } doublyQueue.add(nums[i]); if (i < k - 1) { continue; } maxs[i - k + 1] = doublyQueue.getFirst(); if (doublyQueue.getFirst() == nums[i - k + 1]) { doublyQueue.removeFirst(); } } return maxs; }}

 

转载于:https://www.cnblogs.com/harrygogo/p/4658317.html

你可能感兴趣的文章
【HAOI2006】旅行(并查集暴力)
查看>>
css实现文本超出部分省略号显示
查看>>
留言板
查看>>
vue-router组件状态刷新消失的问题
查看>>
Android UI开发第十四篇——可以移动的悬浮框
查看>>
java8的一些用法
查看>>
(十)Hive分析窗口函数(二) NTILE,ROW_NUMBER,RANK,DENSE_RANK
查看>>
2018-11-19站立会议内容
查看>>
STM32 通用定时器相关寄存器
查看>>
【题解】1621. 未命名
查看>>
字符串加密算法
查看>>
Oracle的实例恢复解析
查看>>
UICollectionView cellForItemAt 不被调用
查看>>
巧用网盘托管私人Git项目
查看>>
python全栈脱产第19天------常用模块---shelve模块、xml模块、configparser模块、hashlib模块...
查看>>
[LeetCode] House Robber
查看>>
virtualbox中kali虚拟机安装增强功能
查看>>
java生成六位验证码
查看>>
iOS的MVP设计模式
查看>>
stringstream
查看>>