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
思路:
queue size大于window size,把queue顶部的元素弹出,同时从summary中减去这个元素,除以size大小得到average。
Complexity: time O(1), space O(window size)
class MovingAverage {
private Queue<Integer> queue;
private double sum = 0.0;
private int windowSize = 0;
/** Initialize your data structure here. */
public MovingAverage(int size) {
queue = new LinkedList<Integer>();
this.windowSize = size;
}
public double next(int val) {
queue.add(val);
if (queue.size() > this.windowSize) {
sum = sum - queue.poll();
}
sum = sum + val;
return sum / queue.size();
}
}
/**
* Your MovingAverage object will be instantiated and called as such:
* MovingAverage obj = new MovingAverage(size);
* double param_1 = obj.next(val);
*/