当前位置:网站首页>leetcode-每日一题剑指 Offer II 041. 滑动窗口的平均值(队列模拟)
leetcode-每日一题剑指 Offer II 041. 滑动窗口的平均值(队列模拟)
2022-07-31 05:10:00 【lin钟一】
题目链接:https://leetcode.cn/problems/qIsx9U/
思路
方法一、队列模拟
直接想法
题目要求我们计算滑动窗口里所有数的平均值,给定了窗口大小size,我们在窗口里的数字个数不超过窗口大小时,按照个数计算平均值,一旦超过窗口大小,我们则需要移动窗口,计算当前窗口里的平均值
算法
- 设计MovingAverage结构体存放窗口大小size,当前窗口数总和sum,记录当前窗口的数 num数组
- Constructor 函数用于把窗口大小size记录在MovingAverage结构体里
- Next方法用于计算窗口平均值
1)当前窗口数字个数不超过窗口大小,按照个数计算平均值
2)当前窗口数字个数超过窗口大小,需要移动窗口,计算当前窗口里的平均值
代码示例
type MovingAverage struct {
size int
sum int
num []int
}
/** Initialize your data structure here. */
func Constructor(size int) MovingAverage {
return MovingAverage{
size: size,
}
}
func (m *MovingAverage) Next(val int) float64 {
//超过窗口大小,需要移动窗口
if len(m.num) == m.size{
m.sum -= m.num[0]
m.num = m.num[1:]
}
m.sum += val
m.num = append(m.num, val)
return float64(m.sum) / float64(len(m.num))
}
/** * Your MovingAverage object will be instantiated and called as such: * obj := Constructor(size); * param_1 := obj.Next(val); */
复杂度分析
- 时间复杂度:O(1) 初始化和调用Next方法都只需要O(1)的时间
- 空间复杂度:O(size) 其中size是窗口大小,空间复杂度主要取决于窗口大小,窗口里的数字个数不会超过size
边栏推荐
- Lock wait timeout exceeded解决方案
- The process and specific code of sending SMS verification code using flask framework
- The TOKEN value of Kubernetes joining the cluster expires
- Why use Flink and how to get started with Flink?
- 快速掌握并发编程 --- 基础篇
- Interviewer, don't ask me to shake hands three times and wave four times again
- C语言指针详解
- Swordsman Offer Special Assault Edition --- Day 3
- 剑指offer专项突击版 ---第 5 天
- About the problems encountered by Xiaobai installing nodejs (npm WARN config global `--global`, `--local` are deprecated. Use `--location=glob)
猜你喜欢
MySQL-如何分库分表?一看就懂
C语言实验五 循环结构程序设计(二)
Sword Point Offer Special Assault Edition ---- Day 2
【MySQL8入门到精通】基础篇- Linux系统静默安装MySQL,跨版本升级
剑指offer基础版 ----- 第28天
The interviewer asked me how to divide the database and the table?Fortunately, I summed up a set of eight-part essays
数据库上机实验5 数据库安全性
剑指offer专项突击版 ---- 第 6 天
Interviewer: If the order is not paid within 30 minutes, it will be automatically canceled. How to do this?
Object Detection Study Notes
随机推荐
闭包(五)----一个常见的循环
find、filter、map的区别
Proteus 8 Professional安装教程
12 【nextTick 过渡与动画】
面试官:生成订单30分钟未支付,则自动取消,该怎么实现?
Swordsman Offer Special Assault Edition ---- Day 6
Distributed transaction processing solution big PK!
MYSQL一站式学习,看完即学完
三子棋讲解(C语言)
初涉C语言
uni-app进阶之创建组件/原生渲染【day9】
闭包(四)----IIFE
Quickly master concurrent programming --- the basics
a different object with the same identifier value was already associated with the session
数据库上机实验3 连接查询和分组查询
剑指offer基础版 --- 第22天
剑指offer基础版 ---- 第29天
剑指offer基础版 --- 第24天
Qt Creator + CMake 运行调试总会自动 build 所有目标
08 【生命周期 组件】