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

题目:给定一个数组和滑动窗口的大小,找出所有滑动窗口里数值的最大值。例如,如果输入数组{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]}。

牛客网:链接

# -*- coding:utf-8 -*-
class Solution:
    def maxInWindows(self, num, size):
        # write code here
        if size > len(num) or size == 0:
            return []

        head = 0
        tail = size - 1
        res = []
        result = []
        while tail < len(num):
            res = num[head]
            for i in num[head+1:tail+1]:
                if i > res:
                    res = i
            head += 1
            tail += 1
            result.append(res)

        return result

if __name__ == '__main__':
    a = Solution()
    b = a.maxInWindows([2,3,4,2,6,2,5,1], 3)
    print(b)

其实就是:

# -*- coding:utf-8 -*-
class Solution:
    def maxInWindows(self, num, size):
        # write code here
        if size > len(num) or size == 0:
            return []

        length = len(num)
        result = []
        for i in range(length+1-size):
            result.append(max(num[i:i+size]))

        return result

猜你喜欢

转载自blog.csdn.net/mengmengdajuanjuan/article/details/82690743