[practice js] a plain solution...


  • 0
    M

    turns out js is not supported here : ]

    public class MovingAverage {
        
        private Deque<Integer> slidingWindow;
        private int currentSum;
        private int windowSizeLimit;
    
        /** Initialize your data structure here. */
        public MovingAverage(int size) {
            slidingWindow = new ArrayDeque<>(0);
            currentSum = 0;
            windowSizeLimit = size;
        }
        
        public double next(int val) {
            if (slidingWindow.size() < windowSizeLimit) {
                slidingWindow.addLast(val);
                currentSum += val;
                return currentSum * 1.0 / slidingWindow.size();
            }
            currentSum -= slidingWindow.removeFirst();
            slidingWindow.addLast(val);
            currentSum += val;
            return currentSum * 1.0 / windowSizeLimit;
        }
    }
    
    /**
     * 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.