您的位置:首页 > 其它

算法分析课每周练习 Sliding Window Maximum

2017-06-26 23:41 357 查看
题目

Sliding Window Maximum

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.

分析

传说中的单调队列

from collections import deque
class Solution:
"""
@param nums: A list of integers.
@return: The maximum number inside the window at each moving.
"""
def maxSlidingWindow(self, nums, k):
# write your code here
q = deque()
result = []
if len(nums) < k or k == 0:
return []

n = len(nums)
for i in xrange(n):
while len(q) and nums[q[-1]] < nums[i]:
q.pop()
q.append(i)

if i < k - 1:
continue

while len(q) and q[0] <= i - k:
q.popleft()

re
4000
sult.append(nums[q[0]])

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: