Simple Java solution use Queue


  • 0
    E
    public class MovingAverage {
        private Queue<Integer> window;
        int windowSize;
        /** Initialize your data structure here. */
        public MovingAverage(int size) {
            window = new LinkedList<Integer>();
            this.windowSize = size;
        }
        
        public double next(int val) {
            if(window.size() < windowSize){
                window.offer(val);
            } else {
                window.poll();
                window.offer(val);
            }
    
            int sum = 0;
            for(int num : window){
                sum += num;
            }
            return (double)sum / window.size();
        }
    }

Log in to reply
 

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