Given a stream of integers and a window size, calculate the moving average of all integers in the sliding window.
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
维护一个队列,保持size不大于设置的size值,队列size达到这个值得时候,去掉最早的数字,更新队列中数字的总和
class MovingAverage {
private LinkedList<Integer> queue;
private int sum;
private int size;
/** Initialize your data structure here. */
public MovingAverage(int size) {
this.queue = new LinkedList<Integer>();
this.size = size;
}
public double next(int val) {
this.queue.offer(val);
sum += val;
if(this.queue.size() == size + 1) {
sum -= this.queue.poll();
}
return sum * 1.0 / this.queue.size();
}
}
/**
* Your MovingAverage object will be instantiated and called as such:
* MovingAverage obj = new MovingAverage(size);
* double param_1 = obj.next(val);
*/