题解 | #滑动窗口的最大值#
滑动窗口的最大值
https://www.nowcoder.com/practice/1624bc35a45c42c0bc17d17fa0cba788
class Solution:
    def maxNum(self, num:List[int]):
        maxx = -10001
        while num:
            tmp = num.pop()
            if tmp > maxx:
                maxx = tmp
        return maxx
    def maxInWindows(self , num: List[int], size: int) -> List[int]:
        # write code here
        if size > len(num) or size == 0:
            return None
        
        res = []
        for i in range(len(num) - size+1):
            tmp = num[i:i+size]
            
            res.append(self.maxNum(tmp))
        
        return res
- 先写一个求数组中最大值的函数,因为每一个滑动窗口都是一个数组;
 - 判断特殊情况,当窗口尺寸大于原始数组长度或窗口尺寸等于0的时候,返回空数组;
 - 每次获取一个滑动窗口,调用求最大值的函数,得到滑动窗口中的最大值,并将其添入到结果数组内。
 
时间复杂度为O(NM),空间复杂度为O(N)。
查看6道真题和解析

