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
class MovingAverage { Queue s = new LinkedList(); double d = 0; int xsize; /** Initialize your data structure here. */ public MovingAverage(int size) { xsize = size; } public double next(int val) { d += val; if(s.size()>= xsize){ d -= (double)s.poll(); } s.add(val); return d/s.size(); } } /** * Your MovingAverage object will be instantiated and called as such: * MovingAverage obj = new MovingAverage(size); * double param_1 = obj.next(val); */ This siteOriginal articleAll follow "Attribution-NonCommercial-ShareAlike 4.0 License (CC BY-NC-SA 4.0)Please retain the following annotations when sharing or adapting:
Original author:Jake Tao,source:「346. Moving Average from Data Stream」