346. Moving Average from Data Stream
Problem description:
Given a stream of integers and a window size, calculate the moving average of all integers in the sliding window.
Example:1
2
3
4
5MovingAverage 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
Solution:
The idea is to use a queue to store the input and check if the size exceed the limit.
1 | class MovingAverage { |
time complexity: $O(1)$
space complexity: $O(n)$
reference:
https://goo.gl/R1YzHh