暴力解法
class Solution:
def maxInWindows(self, num, size):
# write code here
lens = len(num)
result = []
if size == 0:
return []
for i in range(lens-size+1):
content = num[i:i+size]
result.append(max(content))
return result
deque:
import collections
class Solution:
def maxInWindows(self, num, size):
# write code here
lens = len(num)
result = []
deque_ = collections.deque()
if size == 0:
return result
for i in range(lens):
if len(deque_) < size-1:
deque_.append(num[i])
else:
deque_.append(num[i])
result.append(max(deque_))
deque_.popleft()
return result
改进版deque 参考
用deque双端队列存储index,用于判断该值得索引是否还存在在滑动窗口内
- 先判断队列中的第一个元素索引是否还在滑动窗口内,如果不在则弹出第一个元素
- 然后判断遍历的元素num[i]是否大于队列最后一个index所对应元素,大于则弹出该索引,将当前index加入队列
- 判断i是否大于size-1,是则添加索引为deque_[0]的元素,即为滑动窗口中最大的数
import collections
class Solution:
def maxInWindows(self, num, size):
# write code here
lens = len(num)
result = []
deque_ = collections.deque()
if size == 0:
return result
for i in range(lens):
if deque_ and (i-deque_[0] >= size):
deque_.popleft()
while deque_ and num[deque_[-1]] < num[i]:
deque_.pop()
deque_.append(i)
if i>=(size-1):
result.append(num[deque_[0]])
return result