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
This problem defines a MovingAverage class, which can be stored in a fixed number, and then each time we read a number, if the total number after adding this number is greater than the number of limits, then we remove the first number entered, and then return the updated average, This FIFO feature works best with queue queues, and we also need a double variable sum to record the sum of all current numbers so that if there are no more than the limit, then sum is added to the number, and if it is exceeded, sum subtracts the first number first. Add this number and then return the sum divided by the number of queues:
classMovingAverage { Public: MovingAverage (intsize) { This->size =size; Sum=0; } DoubleNextintval) { if(Q.size () >=size) {Sum-=Q.front (); Q.pop (); } Q.push (Val); Sum+=Val; returnSum/q.size (); } Private: Queue<int>Q; intsize; Doublesum;};
Leetcode all in one topic summary (continuous update ...)
[Leetcode] Moving Average from data stream moving an average from a stream