Moving Average from Data Stream
Description
null
Solution(javascript)
// /** 1: 直接往后加, 空间没有优化
// * Initialize your data structure here.
// * @param {number} size
// */
// const MovingAverage = function (size) {
// this.size = size
// this.sum = 0
// this.queue = []
// this.front = 0
// }
// /**
// * @param {number} val
// * @return {number}
// */
// MovingAverage.prototype.next = function (val) {
// this.queue.push(val)
// this.sum += val
// if (this.queue.length - this.front > this.size) {
// this.sum -= this.queue[this.front++]
// }
// return this.sum / (this.queue.length - this.front)
// }
/** 2: 空间优化
* Initialize your data structure here.
* @param {number} size
*/
const MovingAverage = function (size) {
this.size = size
this.sum = 0
this.queue = new Array(size).fill(0)
this.index = 0
}
/**
* @param {number} val
* @return {number}
*/
MovingAverage.prototype.next = function (val) {
const currentIndex = (this.index++) % this.size
this.sum += val - this.queue[currentIndex]
this.queue[currentIndex] = val
return this.sum / Math.min(this.index, this.size)
}