Moving Average from Data Stream

Queue, Design

Easy

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

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

Analysis

用Queue来实现先进先出这样的模式,同时根据应用场景,只需要计算均值,因此额外存一个元素总和sum即可,随着poll(), offer()来更新sum。

可用LinkedList,或者固定长度的array。

算法复杂度 O(1) time, O(k) space

Solution

Queue (Implemented with LinkedList)

(137ms 59.29%)

Another simpler implementation using LinkedList as Queue

Using ArrayDeque

Using fixed length Array (Circular Queue)

(74 ms, faster than 100.00%, 43 MB, less than 59.43%)

用固定长度Array,insertIdx作为下一个数字的位置,每次next()时,要先更新当前sum,再加上新的val。同时要注意的是追踪目前填入了多少个数字,如果小于window长度,则需要用当前填入数字的计数作为分母计算average。

Another implementation

Last updated

Was this helpful?