通过万岁!!!
- 题目:给你一个size,表示一个滑动窗口的大小,然后让你往窗口中加数。并求他的平均值。但是窗口最大为size,如果小于size,就是已有元素的平均值。
- 思路:用队列,然后定义一个sum,表示已有的值,并且保证队列长度不会超过size。
- 技巧:队列
java代码
class MovingAverage {
Queue<Integer> queue;
int size;
int sum = 0;
int max;
/**
* Initialize your data structure here.
*/
public MovingAverage(int size) {
queue = new LinkedList<>();
this.size = size;
max = size;
}
public double next(int val) {
if (size > 0) {
queue.add(val);
sum += val;
size--;
return sum * 1.0 / (max - size);
} else {
queue.add(val);
sum += val;
sum -= queue.remove();
return sum * 1.0 / max;
}
}
}
- 总结:题目不是很难。但是要注意使用队列。