class MovingAverage {
/** Initialize your data structure here. */
int size;
LinkedList<Integer> list;
double ans = 0;
/** Initialize your data structure here. */
public MovingAverage(int size) {
list = new LinkedList<>();
this.size = size;
}
public double next(int val) {
list.addLast(val);
ans += val;
if (list.size() > size){
ans -= list.getFirst();
list.removeFirst();
}
return ans / list.size();
}
}
/**
* Your MovingAverage object will be instantiated and called as such:
* MovingAverage obj = new MovingAverage(size);
* double param_1 = obj.next(val);
*/
使用双端队列,很好实现,具体细节看代码应该很简单