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<Integer> s = new LinkedList<Integer>();
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);
*/
本站原创文章皆遵循“署名-非商业性使用-相同方式共享 3.0 (CC BY-NC-SA 3.0)”。转载请保留以下标注: