Moving Average from Data Stream
https://leetcode.com/problems/moving-average-from-data-stream/description/
Given a stream of integers and a window size, calculate the moving average of all integers in the sliding window.
For example,
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
Thoughts
思路很直观, 用一个queue把新的加进去老的扔出去. 为了计算average, 需要不断更新window sum. 还可以用array和mod模拟queue的效果.
Code
Analysis
时空复杂度O(N).
Last updated
Was this helpful?