My Simple Java Solution using Queue


  • 0
    R
    class MovingAverage {
        int total = 0, size = 0;
        Queue<Integer> queue = new LinkedList<>();
        /** Initialize your data structure here. */
        public MovingAverage(int size) {
            this.size = size;
        }
        
        public double next(int val) {
            if(queue.size() == size){
                total -= queue.poll();
            }
            queue.add(val);
            total += val;
            return (double) total/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.