【剑指offer】滑动窗口的最大值

题目描述

给定一个数组和滑动窗口的大小,找出所有滑动窗口里数值的最大值。例如,如果输入数组{2,3,4,2,6,2,5,1}及滑动窗口的大小3,那么一共存在6个滑动窗口,他们的最大值分别为{4,4,6,6,6,5}; 针对数组{2,3,4,2,6,2,5,1}的滑动窗口有以下6个: {[2,3,4],2,6,2,5,1}, {2,[3,4,2],6,2,5,1}, {2,3,[4,2,6],2,5,1}, {2,3,4,[2,6,2],5,1}, {2,3,4,2,[6,2,5],1}, {2,3,4,2,6,[2,5,1]}。


思路:O(nk)解法

# -*- coding:utf-8 -*-
class Solution:
    def maxInWindows(self, num, size):
        # write code here
        if size == 0:
            return []
        res = []
        for i in range(len(num)-size+1):
            res.append(max(num[i:i+size]))
        return res
思路二:O(n)解法

/*思路就是采用双端队列,队列中的头节点保存的数据比后面的要大。
       比如当前假如的数据比队尾的数字大,说明当前这个数字最起码在从现在起到后面的过程中可能是最大值
       ,而之前队尾的数字不可能最大了,所以要删除队尾元素。
       此外,还要判断队头的元素是否超过size长度,由于存储的是下标,所以可以计算得到;
       特别说明,我们在双端队列中保存的数字是传入的向量的下标;
     */
# -*- coding:utf-8 -*-
class Solution:
    def maxInWindows(self, num, size):
        # write code here
        if not num or size <= 0:
            return []
        res = []
        if len(num) >= size:
            queue = []
            for i in range(size):
                while queue and num[queue[-1]] < num[i]:
                    queue.pop()
                queue.append(i)
                
            for i in range(size, len(num)):
                res.append(num[queue[0]])
                while queue and num[queue[-1]] < num[i]:
                    queue.pop()
                if len(queue) > 0 and queue[0] <= i - size:
                    queue.pop(0)
                queue.append(i)
            res.append(num[queue[0]])
        return res


评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值