Super fast/easy 150ms Java Deque<Double> solution


  • 0
    F

    Add to Deque normalized with the capacity. If the capacity was not met yet , just multiply capacity/current_size to normalize.

    public class MovingAverage {
        int capacity;
        double capacityD;
        Deque<Double> deque;
    
        /**
         * Initialize your data structure here.
         */
        public MovingAverage(int size) {
            this.capacity = size;
            this.capacityD = (double)size;
            this.deque = new ArrayDeque<>(size + 1);
        }
    
        double sum = 0;
    
        public double next(int val) {
            double curr = (val/capacityD);
            deque.addFirst(curr);
            sum += curr;
            if (deque.size() > capacity) {
                sum -= deque.removeLast();
                return sum;
            } else {
                return sum * capacityD/(double)deque.size();
            }
    
    
        }
    }
    

Log in to reply
 

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