11 lines Python solution using deque


  • 0
    class Solution(object):
        def maxSlidingWindow(self, nums, k):
            """
            :type nums: List[int]
            :type k: int
            :rtype: List[int]
            """
            from collections import deque
            res = []            
            q = deque()
            
            for i in xrange(0, len(nums)):
                while q and q[0][1] <= i-k:
                    q.popleft()
                while q and nums[i] > q[-1][0]:
                    q.pop()
                q.append((nums[i], i))
                res.append(q[0][0])
    
            return res[k-1:]
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.