LeetCode刷题实战346:数据流中的移动平均值
Given a stream of integers and a window size, calculate the moving average of all integers in the sliding window.
示例
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
思路:一个队列记录数字,用一个变量记录窗口和即可,每次更新窗口和。
解题
public class MovingAverage {
private double previousSum = 0.0;
private int maxSize;
private Queue<Integer> currentWindow;
/** Initialize your data structure here. */
public MovingAverage(int size) {
currentWindow = new LinkedList<Integer>();
maxSize = size;
}
public double next(int val) {
if(currentWindow.size()==maxSize){
previousSum -= currentWindow.remove();
}
currentWindow.add(val);
previousSum += val;
return previousSum/currentWindow.size();
}
}