Java Solution Using Queue


  • 0
    A
    public class MovingAverage {
    
        private Queue<Integer> queue;
        private int maxSize;
        private double sum = 0;
    
        /** Initialize your data structure here. */
        public MovingAverage(final int maxSize) {
            this.maxSize = maxSize;
            queue = new LinkedList<>();
        }
    
        public double next(final int value) {
            queue.offer(value);
            sum += value;
            if (queue.size() > maxSize) {
                sum -= queue.poll();
            }
            return sum / queue.size();
        }
    }
    

Log in to reply
 

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