当前位置: 首页 > news >正文

Study Plan For Algorithms - Part35

1. 滑动窗口的最大值
给定一个数组 nums 和滑动窗口的大小 k,请找出所有滑动窗口里的最大值。
方法一:

def maxSlidingWindow(nums, k):queue = []res = []if not nums:return queuefor r in range(len(nums)):l = r - k + 1if l > 0 and queue[0] == nums[l - 1]:queue.pop(0)while queue and queue[-1] < nums[r]:queue.pop()queue.append(nums[r])if l >= 0:res.append(queue[0])return res

方法二:

import heapqdef maxSlidingWindow(nums, k):n = len(nums)res = []window = []for i in range(n):heapq.heappush(window, (-nums[i], i))if window[0][1] <= i - k:heapq.heappop(window)if i >= k - 1:res.append(-window[0][0])return res

方法三:

def maxSlidingWindow(nums, k):n = len(nums)res = []for i in range(n - k + 1):max_val = nums[i]for j in range(i, i + k):max_val = max(max_val, nums[j])res.append(max_val)return res

http://www.mrgr.cn/news/33906.html

相关文章:

  • 快速了解使用路由器
  • 证书学习(五)Java实现RSA、SM2证书颁发
  • 【学习笔记】手写 Tomcat 五
  • Python | Leetcode Python题解之第430题扁平化多级双向链表
  • YOLO航拍车辆和行人识别
  • 实战篇 | WSL迁移Linux系统到非系统盘(完整实操版)
  • 旋转机械故障数据集 全网首发
  • 自然语言处理的算法:从SVM到Attention
  • UIKit-Camera
  • 滚动轴承故障诊断、预测与分类综合数据集
  • C语言 | Leetcode C语言题解之第430题扁平化多级双向链表
  • 全网最适合入门的面向对象编程教程:51 Python函数方法与接口-使用Zope实现接口
  • C++ | Leetcode C++题解之第429题N叉树的层序遍历
  • 6.7泊松噪声
  • 安装 Anaconda
  • Renesas R7FA8D1BH (Cortex®-M85)的 General PWM的应用实践
  • OSError: Missing dependencies for SOCKS support
  • Java数据库连接——JDBC
  • 智能农业系统——土壤养分运移转化
  • 一些迷你型信息系统 - 2