python leetcode 239. Sliding Window Maximum

用一个双向队列来维护

class Solution(object):
    def maxSlidingWindow(self, nums, k):
        """
        :type nums: List[int]
        :type k: int
        :rtype: List[int]
        """
        if nums==[]:
            return []
        if len(nums)<=k:
            return [max(nums)]
        import collections 
        d = collections.deque()
        res=[]
        #保存的是下标
        for i in range(len(nums)):
            if len(d) >0 and i-d[0] == k :
                d.popleft()
            while len(d) >0 and nums[i]>=nums[d[-1]]:
                d.pop()
            
            d.append(i)
            if i>=k-1:
                res.append(nums[d[0]])
        return res

猜你喜欢

转载自blog.csdn.net/Neekity/article/details/85091296