首页 技术 正文
技术 2022年11月14日
0 收藏 562 点赞 2,975 浏览 1199 个字

[抄题]:

Given a stream of integers and a window size, calculate the moving average of all integers in the sliding window.

For example,

MovingAverage m = new MovingAverage(3);
m.next(1) = 1
m.next(10) = (1 + 10) / 2
m.next(3) = (1 + 10 + 3) / 3
m.next(5) = (10 + 3 + 5) / 3

[暴力解法]:

时间分析:

空间分析:

[奇葩输出条件]:

[奇葩corner case]:

[思维问题]:

以为要分情况讨论除数,没有想数据结构

[一句话思路]:

用queue的动态长度避免分类讨论

[输入量]:空: 正常情况:特大:特小:程序里处理到的特殊情况:异常情况(不合法不合理的输入):

[画图]:

[一刷]:

  1. queue刚满足等于时就应除,不够警惕,下次注意
  2. 动态计算时可以初始化为0,不能在方法中重置为0,下次注意

[二刷]:

[三刷]:

[四刷]:

[五刷]:

[五分钟肉眼debug的结果]:

[总结]:

[复杂度]:Time complexity: O(n) Space complexity: O(n)

[英文数据结构或算法,为什么不用别的数据结构或算法]:

API design的题就是在类中声明引用,在方法中和实际的对象发生连接

  1. queue的实现(具体对象)是linkedlist,都是一条链,不难想象. queue用add也没事

[关键模板化代码]:

先说引用,再说对象

Queue<Integer> q;
int s;
double sum; public MovingAverage(int size) {
q = new LinkedList<Integer>();
s = size;
sum = 0;
}

[其他解法]:

[Follow Up]:

[LC给出的题目变变变]:

[代码风格] :

class MovingAverage {    /** Initialize your data structure here. */
Queue<Integer> q;
int s;
double sum; public MovingAverage(int size) {
q = new LinkedList<Integer>();
s = size;
sum = 0;
} public double next(int val) {
//when the queue just equals the size, poll it out
if (q.size() == s) {
sum -= q.poll();
}
q.add(val);
sum += val;
return sum / q.size();
}
}/**
* Your MovingAverage object will be instantiated and called as such:
* MovingAverage obj = new MovingAverage(size);
* double param_1 = obj.next(val);
*/
相关推荐
python开发_常用的python模块及安装方法
adodb:我们领导推荐的数据库连接组件bsddb3:BerkeleyDB的连接组件Cheetah-1.0:我比较喜欢这个版本的cheeta…
日期:2022-11-24 点赞:878 阅读:9,082
Educational Codeforces Round 11 C. Hard Process 二分
C. Hard Process题目连接:http://www.codeforces.com/contest/660/problem/CDes…
日期:2022-11-24 点赞:807 阅读:5,556
下载Ubuntn 17.04 内核源代码
zengkefu@server1:/usr/src$ uname -aLinux server1 4.10.0-19-generic #21…
日期:2022-11-24 点赞:569 阅读:6,406
可用Active Desktop Calendar V7.86 注册码序列号
可用Active Desktop Calendar V7.86 注册码序列号Name: www.greendown.cn Code: &nb…
日期:2022-11-24 点赞:733 阅读:6,179
Android调用系统相机、自定义相机、处理大图片
Android调用系统相机和自定义相机实例本博文主要是介绍了android上使用相机进行拍照并显示的两种方式,并且由于涉及到要把拍到的照片显…
日期:2022-11-24 点赞:512 阅读:7,815
Struts的使用
一、Struts2的获取  Struts的官方网站为:http://struts.apache.org/  下载完Struts2的jar包,…
日期:2022-11-24 点赞:671 阅读:4,898