leetcode 算法题346 (简单086) 数据流中的移动平均值

leetcode 算法题346 (简单086) 数据流中的移动平均值

  • 题目介绍
给定一个整数数据流和一个窗口大小,根据该滑动窗口的大小,计算其所有整数的移动平均值。
  • 示例

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

  • 解法一
/**
 * Initialize your data structure here.
 * @param {number} size
 */
var MovingAverage = function(size) {
    this.size = size;
    this.list = [];
};

/** 
 * @param {number} val
 * @return {number}
 */
MovingAverage.prototype.next = function(val) {
    let list = this.list;
    list.push(val);
    if(list.length === 1) {
      this.avg = val;
      return this.avg;
    }
    if(list.length > this.size) {
      this.avg += (val - list.shift()) / this.size;
      return this.avg;
    }
    this.avg += (val - this.avg) / list.length;
    return this.avg;
};

/** 
 * Your MovingAverage object will be instantiated and called as such:
 * var obj = new MovingAverage(size)
 * var param_1 = obj.next(val)
 */

执行用时 : 108 ms, 在所有 JavaScript 提交中击败了95.74%的用户

内存消耗 : 43.5 MB, 在所有 JavaScript 提交中击败了100.00%的用户

  • 解法二
/**
 * Initialize your data structure here.
 * @param {number} size
 */
var MovingAverage = function(size) {
    this.size = size;
    this.list = [];
};

/** 
 * @param {number} val
 * @return {number}
 */
MovingAverage.prototype.next = function(val) {
    let list = this.list, i = sum = 0;
    list.push(val);
    if(list.length > this.size) {
      list.shift();
    }
    while(i < list.length) {
      sum += list[i++];
    }
    return sum / i;
};

/** 
 * Your MovingAverage object will be instantiated and called as such:
 * var obj = new MovingAverage(size)
 * var param_1 = obj.next(val)
 */

执行用时 : 132 ms, 在所有 JavaScript 提交中击败了91.94%的用户

内存消耗 : 43.1 MB, 在所有 JavaScript 提交中击败了100.00%的用户

你可能感兴趣的:(#,leetcode,简单,leetcode)