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) = 1m.next (1 +)/2m.next (3) = (1 + 3)/3m.next (5) = (10 + 3 + 5)/3
Title Tags: Design
This topic lets us design a moving average structure, we have an input size, and this size is the window that controls us. Each time a new number comes in, if the current size is less than window, then continue to join. If the new number comes in, the size is full, equal to window size. Then we need to remove the first number and add the new number. You can use ArrayList to mimic the queue implementation, add adds to the end, remove (0) removes the first number. Also set a sum, each time you join, add sum, when full, after each removal, just subtract from sum. This avoids the need to iterate through the queue every time you add a number to the sum of all the numbers.
Java Solution:
Runtime beats 71.48%
Completion Date: 07/09/2017
Keywords: Design
Key point: Using ArrayList to mimic a queue
1 Public classMovingAverage {2 3Arraylist<integer>queue;4 intqueue_size;5 Doublesum;6 /**Initialize your data structure here.*/7 PublicMovingAverage (intsize)8 {9Queue =NewArraylist<>(size);TenQueue_size =size; Onesum = 0; A } - - Public DoubleNextintval) the { - if(queue.size () = = queue_size)//meaning it is full - { -Sum-= queue.get (0);//minus head +Queue.remove (0);//Remove the head - } + AQueue.add (Val);//append the new integer atSum + = val;//add into Sum - - return(Sum/queue.size ()); - } - } - in /** - * Your MovingAverage object would be instantiated and called as such: to * MovingAverage obj = new MovingAverage (size); + * Double param_1 = Obj.next (val); - */
Reference: N/A
Leetcode algorithm topic List- leetcode algorithms Questions list
Leetcode 346. Moving Average from Data Stream (moving average in data flow)