100% Java Solution with Deque


  • 1
    W
    public class MovingAverage {
    
        private int size;
        private double sum;
        private ArrayDeque<Integer> queue;
        public MovingAverage(int size) {
            this.size = size;
            this.sum = 0;
            this.queue = new ArrayDeque<Integer>();
        }
    
        public double next(int val) {
            if (queue.size() == size) {
                sum -= queue.remove();
            }
            queue.offer(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.