滑动窗口的最大值

设定划定窗口的长度,在给定列表上做滑动,求每次滑动的最大值

nums, k = [1,3,-1,-3,5,3,6,7], 3
result = []
# method 1:bf
for i in range(len(nums)-k+1):
    result.append(max(nums[i:i+k]))
print(result)
# method 2:保存中间过程
result = []
first_max = max(nums[:k])
result.append(first_max)
for i in range(1, len(nums)-k+1):
    if first_max == nums[i-1]:
        first_max = max(nums[i:i+k])
        result.append(first_max)
    else:
        first_max = max(first_max, nums[i+k-1])
        result.append(first_max)
# method 3: heap (n*lgk)
nums, k = [1,3,-1,-3,5,3,6,7], 3
nums = [-e for e in nums]
result = []
for i in range(len(nums)-k+1):
    temp = nums[i:i+k]
    heapq.heapify(temp)
    result.append(-heapq.heappop(temp))
result

# method 4: both end queue
nums, k = [1,3,-1,-3,5,3,6,7], 3
n = len(nums)
q = deque()
for i in range(k):
    # 保持队首是最大值
    while q and nums[i] >= nums[q[-1]]:
        q.pop()
    q.append(i)
result = [nums[q[0]]]
for i in range(k, n):
    while q and nums[i] >= nums[q[-1]]:
        q.pop()
    q.append(i)
    while q[0] <= i-k:
        q.popleft()
    result.append(nums[q[0]])
result

 

posted @ 2022-09-08 20:00  今夜无风  阅读(30)  评论(0编辑  收藏  举报