class Solution:
def maxSlidingWindow(self, nums: 'List[int]', k: int) -> 'List[int]':
n = len(nums)
if n==0:
return []
if k==0:
return []
dic = {}
for i in range(k):
dic.update({i:nums[i]}) maxindex = max(dic,key=dic.get)
result = list()
result.append(dic[maxindex]) i=0
j=k
while j<len(nums):
del dic[i]
dic.update({j:nums[j]})
maxindex = max(dic,key=dic.get)
result.append(dic[maxindex])
i+=1
j+=1 return result

显然这是暴力搜索算法,性能比较差,执行时间1800ms,基本上是超时的边缘了。

下面是参考其他人的,执行时间120ms

 class Solution:
def maxSlidingWindow(self, nums: 'List[int]', k: int) -> 'List[int]':
n=len(nums)
stack=[]
ans=[]
for i in range(n):
while stack and nums[i]>nums[stack[-1]]:
stack.pop()
while stack and i-stack[0]>=k:
stack.pop(0)
stack.append(i)
if i>=k-1:
ans.append(nums[stack[0]])
return ans

思路分析:使用滑动窗口,stack是宽度为k的滑动窗口,并且里面的元素是从大到小排列的。

外层滑动窗口每次取的是stack[0],也就是当前滑动个窗口范围内最大的值的下标,存储在stack[0]中。因此nums[stack[0]]就是当前范围的最大值。

leetcode239的更多相关文章

  1. [Swift]LeetCode239. 滑动窗口最大值 | Sliding Window Maximum

    Given an array nums, there is a sliding window of size k which is moving from the very left of the a ...

  2. LeetCode239. Sliding Window Maximum

    Given an array nums, there is a sliding window of size k which is moving from the very left of the a ...

  3. 剑指offer-java

    面试题67 机器人的运动范围 题意: 地上有一个m行和n列的方格.一个机器人从坐标0,0的格子开始移动,每一次只能向左,右,上,下四个方向移动一格,但是不能进入行坐标和列坐标的数位之和大于k的格子. ...

  4. LeetCode-Queue

    简单题 1. 数据流中的移动平均值 $(leetcode-346) 暂无 2. 最近的请求次数(leetcode-933) 写一个 RecentCounter 类来计算最近的请求. 它只有一个方法:p ...

随机推荐

  1. python用schedule模块实现定时任务

    1 import schedule 2 import time 3 4 def test(): 5 print("I'm working...") 6 def test2(): 7 ...

  2. libnids-1.24 使用源码问题

    从网上下载libnids-1.24源码包,解压后./configure安装. 会出现提示 checking for GLIB... configure: error: Package requirem ...

  3. SQL Analytic Functions 分析函数

    应用场景 主要使用在需要分组计算的场景中,根据所需的计算值可以分为两类: 1,排序类:如排序号,相邻记录等 2,聚合类:如平均值,累加求和,最大值,最末值等 语法 分析函数的语法在各大数据库中基本类似 ...

  4. 《Linux内核原理与分析》第八周作业

    课本:第七章 可执行程序工作原理 ELF目标文件格式 目标文件:编译器生成的文件. 目标文件的格式:out格式.COFF格式.PE(windows)格式.ELF(Linux)格式. ELF(Execu ...

  5. fixed 相对于父容器定位

    当一个元素设置为 fixed 或 absolute,不设置 top, left 则会在原位置,而脱离文档流,别的元素可以存在于它之后. 而当使用 fixed 后还想相对于父容器进行定位,或者说在当前位 ...

  6. QT4.8.6-VS2010开发环境配置

    目录 1.下载软件 2.环境配置 3.VAssistX配置 1.下载软件 VS2010下载地址:链接: https://pan.baidu.com/s/1gvPjZWBtSEwW37H1xf2vbA ...

  7. ajax 调用webservice 跨域问题

    注意两点 1. 在webservice的config中加入这段位置 (注意不是调用webservice的webconfig中加入) <system.webServer>     <! ...

  8. c# automapper 使用(一)

    一.最简单的用法 有两个类User和UserDto public class User { public int Id { get; set; } public string Name { get; ...

  9. liunx学习笔记(一:常用命令)

    linux: 在学习linux之前我们应该多少了解windows的一些相关操作,linux也就是类似windows的另一种操作系统,用来管理软硬件的一种应用.在windows下你可以通过鼠标点击相关的 ...

  10. ILBC 规范 2

    接上篇 <ILBC 规范>  https://www.cnblogs.com/KSongKing/p/10354824.html  , ILBC    的 目标 是    跨平台  跨设备 ...