LeetCode239:Sliding Window Maximum

Given an array nums, there is a sliding window of size k which is moving from the very left of the array to the very right. You can only see the k numbers in the window. Each time the sliding window moves right by one position. Return the max sliding window.

Example:

Input: nums = [1,3,-1,-3,5,3,6,7], and k = 3
Output: [3,3,5,5,6,7] 
Explanation: 

Window position                Max
---------------               -----
[1  3  -1] -3  5  3  6  7       3
 1 [3  -1  -3] 5  3  6  7       3
 1  3 [-1  -3  5] 3  6  7       5
 1  3  -1 [-3  5  3] 6  7       5
 1  3  -1  -3 [5  3  6] 7       6
 1  3  -1  -3  5 [3  6  7]      7

Note: 
You may assume k is always valid, 1 ≤ k ≤ input array's size for non-empty array.

Follow up:
Could you solve it in linear time?


LeetCode:链接

剑指offer同题: 剑指Offer_编程题64:滑动窗口的最大值(双向队列)

我们可以使用一个双端队列deque,接下来我们以数组{2,3,4,2,6,2,5,1}为例,细说整体思路。
数组的第一个数字是2,把它存入队列中。第二个数字是3,比2大,所以2不可能是滑动窗口中的最大值,因此把2从队列里删除,再把3存入队列中。第三个数字是4,比3大,同样的删3存4。此时滑动窗口中已经有3个数字,而它的最大值4位于队列的头部。
第四个数字2比4小,但是当4滑出之后它还是有可能成为最大值的,所以我们把2存入队列的尾部。下一个数字是6,比4和2都大,删4和2,存6。就这样依次进行,最大值永远位于队列的头部。
但是我们怎样判断滑动窗口是否包括一个数字?应该在队列里存入数字在数组里的下标,而不是数值。当一个数字的下标与当前处理的数字的下标之差大于或者相等于滑动窗口大小时,这个数字已经从窗口中滑出,可以从队列中删除

class Solution(object):
    def maxSlidingWindow(self, nums, k):
        """
        :type nums: List[int]
        :type k: int
        :rtype: List[int]
        """
        if not len(nums) or not k or k > len(nums):
            return []
        '''结果列表'''
        result = []
        '''双端列表 左端存储最大值 右端存储小值'''
        deque = []
        '''判断第一个窗口'''
        for i in range(k):
            while deque and nums[i] > nums[deque[-1]]:
                deque.pop()
            deque.append(i)
        for i in range(k, len(nums)):
            result.append(nums[deque[0]])
            '''deque存储的值是从大到小的值 [0]的位置是最大值 右端存的值可以比最大值小 但是不能比最大值大 8 5 4'''
            '''如果当前的值比右端的值小 可以保留 因为窗口滑动之后 还是有可能成为最大值的'''
            '''如果比右端的值大 右端的值就不能留了 这个循环每次只考虑多滑动一个点和之前点的情况'''
            '''最大值永远位于队列的头部'''
            while deque and nums[i] > nums[deque[-1]]:
                deque.pop()
            '''如果最大值和当前值的坐标差已经大于等于窗口大小了 说明数字已经从窗口滑出了 应该删除了'''
            if deque and i - deque[0] >= k:
                deque.pop(0)
            deque.append(i)
        '''滑到末尾的值'''
        result.append(nums[deque[0]])
        return result

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值