跳至主要內容

346. Moving Average from Data Stream


346. Moving Average from Data Streamopen in new window

🟢   🔖  设计 队列 数组 数据流  🔗 LeetCodeopen in new window

题目

Given a stream of integers and a window size, calculate the moving average of all integers in the sliding window.

Implement the MovingAverage class:

  • MovingAverage(int size) Initializes the object with the size of the window size.
  • double next(int val) Returns the moving average of the last size values of the stream.

Example:

Input

["MovingAverage", "next", "next", "next", "next"]

[[3], [1], [10], [3], [5]]

Output

[null, 1.0, 5.5, 4.66667, 6.0]

Explanation

MovingAverage movingAverage = new MovingAverage(3);

movingAverage.next(1); // return 1.0 = 1 / 1

movingAverage.next(10); // return 5.5 = (1 + 10) / 2

movingAverage.next(3); // return 4.66667 = (1 + 10 + 3) / 3

movingAverage.next(5); // return 6.0 = (10 + 3 + 5) / 3

Constraints:

  • 1 <= size <= 1000
  • -10^5 <= val <= 10^5
  • At most 10^4 calls will be made to next.

题目大意

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

实现 MovingAverage 类:

  • MovingAverage(int size) 用窗口大小初始化对象。
  • double next(int val) 返回流的最后一个大小值的移动平均值。

解题思路

这道题可以使用队列来做,用一个队列记录数字,用一个变量记录窗口和,每次更新窗口和。

代码

class MovingAverage {
  constructor(size) {
    this.size = size;
    this.queue = [];
    this.sum = 0;
  }
  next(val) {
    if (this.queue.length < this.size) {
      this.queue.push(val);
      this.sum += val;
    } else {
      this.sum -= this.queue.shift();
      this.queue.push(val);
    }
    return this.sum / this.queue.length;
  }
}