leetcode239
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的更多相关文章
- [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 ...
- 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 ...
- 剑指offer-java
面试题67 机器人的运动范围 题意: 地上有一个m行和n列的方格.一个机器人从坐标0,0的格子开始移动,每一次只能向左,右,上,下四个方向移动一格,但是不能进入行坐标和列坐标的数位之和大于k的格子. ...
- LeetCode-Queue
简单题 1. 数据流中的移动平均值 $(leetcode-346) 暂无 2. 最近的请求次数(leetcode-933) 写一个 RecentCounter 类来计算最近的请求. 它只有一个方法:p ...
随机推荐
- [Ajax] 如何使用Ajax传递多个复选框的值
HTML+JavaScript代码: <!DOCTYPE html> <html> <head> <meta charset="UTF-8" ...
- python day20面向对象-属性,类方法,静态方法
一.属性的初识 # class Person: # # def __init__(self,name,hight,weight): # self.name = name # self.__hight ...
- 用rz、sz命令在Xshell传输文件
用rz.sz命令在Xshell传输文件 2014-03-27 14:38:17 标签:用rz.sz命令在Xshell传输文件 Xshell很好用,然后有时候想在windows和linux之间上传或下载 ...
- 6.移动端App安装包的测试用例
安装 安装手册是否规范,是否简洁,是否通俗易懂. 安装手册是否齐全,正确,有改动时,文档是否同步更新 直接复制安装程序到电脑上,能否正常安装 按安装手册给出的步骤进行安装,安装是否正确 查看在安装过程 ...
- C# ModBus Tcp读写数据 与服务器进行通讯
前言 本文将使用一个NuGet公开的组件技术来实现一个ModBus TCP的客户端,方便的对Modbus tcp的服务器进行读写,这个服务器可以是电脑端C#设计的,也可以是PLC实现的,也可以是其他任 ...
- gitlab 同步小脚本
gitlab 是公司中的代码仓库,如何保证两台机器同步呢 公司中使用的是docker那么久使用docker进行演示了也方便以后的工作查找资料 附:脚本 #!/bin/bash docker stop ...
- [LeetCode&Python] Problem 844. Backspace String Compare
Given two strings S and T, return if they are equal when both are typed into empty text editors. # m ...
- Linux 练习题(2)
3. 请使用命令行展开功能来完成以下练习: (1). 创建/tmp目录下的:a_c, a_d, b_c, b_d [root@db146 ~]# mkdir /tmp/{a,b}_{c,d ...
- CVE-2017-12615和CVE-2017-12616
Tomcat代码执行漏洞分析测试 1. 漏洞花絮 2017年9月19日,Apache Tomcat官方确认并修复了两个高危漏洞,漏洞CVE编号:CVE-2017-12615和CVE-20 ...
- PythonStudy——数据类型总结 Data type summary
按存储空间的占用分(从低到高) 数字 字符串 集合:无序,即无序存索引相关信息,可变.集合中的元素必须是可hash的,即不可变的数据类型. 元组:有序,需要存索引相关信息,不可变 列表:有序,需要存索 ...