136ms Java AC solution, bean 96.81% answer


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

Log in to reply
 

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