[Python手撕]滑動視窗最大值

Duancf發表於2024-09-10
class Solution:
    def maxSlidingWindow(self, nums: List[int], k: int) -> List[int]:

        n = len(nums)
        res = []
        queue = [[0,nums[0]]]

        for i in range(1,k):
            while queue and queue[-1][1]<nums[i]:
                queue.pop(-1)
            queue.append([i,nums[i]])
        res.append(queue[0][1])

        for i in range(k,n):
            while queue and i-queue[0][0]>=k:
                queue.pop(0)
            while queue and queue[-1][1]<nums[i]:
                queue.pop(-1)
            queue.append([i,nums[i]])
            res.append(queue[0][1])

        return res


相關文章