[抄题]:
给出一串整数流和窗口大小,计算滑动窗口中所有整数的平均值。
MovingAverage m = new MovingAverage(3);
m.next(1) = 1 // 返回 1.00000
m.next(10) = (1 + 10) / 2 // 返回 5.50000
m.next(3) = (1 + 10 + 3) / 3 // 返回 4.66667
m.next(5) = (10 + 3 + 5) / 3 // 返回 6.00000
[暴力解法]:
来一个数就存数组,for 循环最近size个数求和取平均返回。
时间分析:size
空间分析:n
[思维问题]:
不知道为什么要定义全局变量:因为两个函数中都要用。
先提前声明,在函数中分别具体实现。
[一句话思路]:
先进先出,用queue实现就行。
[输入量]:空: 正常情况:特大:特小:程序里处理到的特殊情况:异常情况(不合法不合理的输入):
[画图]:
[一刷]:
- 判断queue尺寸,已经满了,就先拿出来 再放进去。
[二刷]:
[三刷]:
[四刷]:
[五刷]:
[五分钟肉眼debug的结果]:
[总结]:
- 方法中只有实现,没有声明。que = new LinkedList<Integer>();即可
[复杂度]:Time complexity: O(n) Space complexity: O(n)
n个点,每个点执行一次。不知道queue都是这样吗?下次注意
[英文数据结构或算法,为什么不用别的数据结构或算法]:
[其他解法]:
前缀和,没有通用性,算了
- 时间分析:方便快速求a数组中某一段的和 前缀和做差法 a[k] + a[k + 1] +... + a[j] = s[j] - s[k -1] 时间复杂度降成o(1)
[Follow Up]:
[LC给出的题目变变变]:
239. Sliding Window Maximum median 一堆数求最值,用堆
773. Sliding Puzzle 最短路,用bfs
[代码风格] :
/ 除号两边要打空格
public class MovingAverage {
/*
* @param size: An integer
*/
private double sum = 0;//
private int size;
private int val;
private Queue<Integer> que; public MovingAverage(int size) {
this.size = size;
que = new LinkedList<Integer>();
} /*
* @param val: An integer
* @return:
*/
public double next(int val) {
this.val = val;
this.sum = sum;
sum += val;
if (que.size() == size) {
sum = sum - que.poll();
}
que.offer(val); return sum / que.size();//
}
}