剑指Offer 64. 滑动窗口的最大值 (其他)

Posted on 2018-10-18 11:04  _hqc  阅读(122)  评论(0编辑  收藏  举报

题目描述

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

题目地址

https://www.nowcoder.com/practice/1624bc35a45c42c0bc17d17fa0cba788?tpId=13&tqId=11217&rp=3&ru=/ta/coding-interviews&qru=/ta/coding-interviews/question-ranking

思路

思路1:

思路2:数组切片

Python

# -*- coding:utf-8 -*-
class Solution:
    def maxInWindows(self, num, size):
        # write code here
        if len(num) < size or size == 0:
            return []
        # 思路1
        # left, right = 0, size-1
        # res = []
        # while right < len(num):
        #     maxindex = left
        #     for j in range(left+1,right+1):
        #         if num[j] > num[maxindex]:
        #             maxindex = j
        #     res.append(num[maxindex])
        #     left += 1
        #     right += 1
        # return res
        # 思路2
        res = []
        for i in range(len(num)-size+1):
            res.append(max(num[i:i+size]))
        return res

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