题目:
给定一个整数数据流和一个窗口大小,根据该滑动窗口的大小,计算其所有整数的移动平均值。
示例:
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
解法 队列
let MovingAverage = function(length){
let arr = [];
this.next = function(num){
if(length === 0) return;
if(arr.length >= length){
arr.shift();
}
arr.push(num);
let sum = arr.reduce(function(prev, cur){
return prev + cur;
}, 0)
return parseInt(sum / arr.length)
}
}