Java Simple Solution


  • 0
    S
    public class MovingAverage {
    
        private int size;
        private Queue<Integer> queue;
        double sum;
        
        /** Initialize your data structure here. */
        public MovingAverage(int size) {
            this.size = size;
            queue = new LinkedList<>();
            sum = 0;
        }
        
        public double next(int val) {
            if(this.queue.size() == size) {
                int head =queue.remove();
                sum-=head;
            }
            queue.add(val);
            sum+=val;
            return sum/queue.size();
        }
    }

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.