Java solution, using queue


  • 0
    C
    public class MovingAverage {
        Deque<Integer> queue;
        int size;
        double sum;
        /** Initialize your data structure here. */
        public MovingAverage(int size) {
            queue = new ArrayDeque<>();
            this.size = size;
            sum = 0;
        }
        
        public double next(int val) {
            queue.addLast(val);
            sum += val;
            if(queue.size() <= size) return sum/queue.size();
            sum -= queue.removeFirst();
            return sum/queue.size();
        }
    }
    
    /**
     * Your MovingAverage object will be instantiated and called as such:
     * MovingAverage obj = new MovingAverage(size);
     * double param_1 = obj.next(val);
     */

Log in to reply
 

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