• LeetCode-239-剑指offer-滑动窗口的最大值-队列与栈-python


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

    思路:

    class Solution:
        def maxInWindows(self, num, size):
            # write code here
            if not num:
                return []
            if size ==0:
                return []
            if len(num)==1:
                return num
            temp,res = [0],[]
            #数组temp中存放着当前窗口的最大值,和按需排列好的次大值,
            # 这些次大值在数组中的位置只能是位于最大之后的,
            # 数组 temp 的最大规模为 size -1。
            for i in range(len(num)):
                # temp[0]中记录第一个最大值的标号(位置) 
                if i-temp[0]>size-1: #代表第一个最大值的位置到当前位置,超出了长度为(size-1)的选定框
                    temp.pop(0)#所以去掉第一个最大值
                while len(temp) !=0 and num[i] >= num[temp[-1]]:#当num当前的值大于或等于num次大值后,替换次大值
                    temp.pop()
                temp.append(i)
                if i>=size-1:#如果当前坐标大于选定框长度,则将最大值放入res表
                    res.append(num[temp[0]])
            return res

     用python 本身的性质,时间复杂度O(n*size)

    # -*- coding:utf-8 -*-
    class Solution:
        def maxInWindows(self, num, size):
            # write code here
            i,res = 0,[]
            while size and i+size -1<len(num):
                res.append(max(num[i:i+size]))
                i+=1
            return res

    双向队列,queue存入num的位置,时间复杂度O(n)

    # -*- coding:utf-8 -*-
    class Solution:
        def maxInWindows(self, num, size):
            # write code here
            queue,res,i = [],[],0
            while size>0 and i<len(num):
                if len(queue)>0 and i-size+1 > queue[0]: #若最大值queue[0]位置过期 则弹出 
                    queue.pop(0)
                while len(queue)>0 and num[queue[-1]]<num[i]: #每次弹出所有比num[i]的数字
                    queue.pop()
                queue.append(i)
                if i>=size-1:
                    res.append(num[queue[0]])
                i += 1
            return res
  • 相关阅读:
    在SQL Server通过DBLINK执行ORACLE存储过程
    WIFI无线网卡全双工
    ORACLE判断日期、时间的字符串是否有效日期、时间
    FN_SPLIT-表值函数, 将字符串转列表
    EBS-从职责到报表名
    LeetCode 791 自定义字符串排序
    cgit——github快速下载器
    Ubuntu 16.04下使用git clone时报“gnutls_handshake() failed: Error in the pull function”错误
    LeetCode 1702 修改后的最大二进制字符串
    一个因编码习惯不正确而产生的BUG
  • 原文地址:https://www.cnblogs.com/ansang/p/11885852.html
Copyright © 2020-2023  润新知