美文网首页leetcode
leetcode 滑动窗口最大值 python

leetcode 滑动窗口最大值 python

作者: DaydayHoliday | 来源:发表于2019-03-28 20:43 被阅读0次

双向队列好

import collections
class Solution(object):
    def maxSlidingWindow(self, nums, k):
        res=[]
        d = collections.deque()
        for i in range(len(nums)):
            if len(d)==0:
                d.append((nums[i],i))
                if i>=k-1:
                    res.append(d[0][0])                
                continue
            if d[0][1]<=i-k:
                d.popleft()
            while len(d)>0:
                tail=d[-1][0]
                if nums[i]<tail:
                    break
                d.pop()
            d.append((nums[i],i))
            if i>=k-1:
                res.append(d[0][0])
        return res

相关文章

网友评论

    本文标题:leetcode 滑动窗口最大值 python

    本文链接:https://www.haomeiwen.com/subject/vjxhbqtx.html