346. Moving Average from Data Stream

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 1:

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
  • -105 <= val <= 105
  • At most 104 calls will be made to next.

Rust Solution

use std::collections::VecDeque;

struct MovingAverage {
    queue: VecDeque<i32>,
    sum: i32,
    size: usize,
}

impl MovingAverage {
    fn new(size: i32) -> Self {
        MovingAverage {
            queue: VecDeque::new(),
            sum: 0,
            size: size as usize,
        }
    }

    fn next(&mut self, val: i32) -> f64 {
        self.sum += val;
        self.queue.push_back(val);
        if self.queue.len() > self.size {
            if let Some(front) = self.queue.pop_front() {
                self.sum -= front;
            }
        }
        self.sum as f64 / self.queue.len() as f64
    }
}

#[test]
fn test() {
    use assert_approx_eq::assert_approx_eq;
    let mut m = MovingAverage::new(3);
    assert_approx_eq!(m.next(1), 1f64);
    assert_approx_eq!(m.next(10), 5.5f64);
    assert_approx_eq!(m.next(3), 14f64 / 3f64);
    assert_approx_eq!(m.next(5), 6f64);
}

Having problems with this solution? Click here to submit an issue on github.