239 Sliding Window Maximum

239 Sliding Window Maximum

这道题是 double-ended queue 的最典型应用

class Solution:
    # @param {integer[]} nums
    # @param {integer} k
    # @return {integer[]}
    def maxSlidingWindow(self, nums, k):
        if nums == []:
            return []
        ans,tmp = [], []
        for i in range(0, k):
            while tmp != [] and nums[i] > nums[tmp[-1]]:
                tmp.pop()
            tmp.append(i)
        for i in range(k, len(nums)):
            ans.append(nums[tmp[0]])
            while tmp != [] and nums[i] > nums[tmp[-1]]:
                tmp.pop()
            tmp.append(i)
            while tmp != [] and tmp[0] <= i-k:
                tmp.pop(0)
        ans.append(nums[tmp[0]])
        return ans

 

posted @ 2015-07-19 13:06  dapanshe  阅读(139)  评论(0编辑  收藏  举报