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.
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
This first-in, first-out feature is most suitable for using queues, and we also need a double variable sum to record the sum of all current numbers.
After entering this new number,
If the limit is not exceeded, sum plus this number,
If it exceeds, then sum first subtracts the earliest number, then adds this number, and then returns the number of sum divided by the queue