Simple O(1) Java solution


  • 3
    N

    Maintain a sum and count for elements in queue.

    public class MovingAverage {
    
        /** Initialize your data structure here. */
        Queue queue = new LinkedList();
        int size;
        int count;
        int sum;
        
        public MovingAverage(int size) {
            this.size = size;
        }
        
        public double next(int val) {
            if (count == size) {
                sum = sum - (int)queue.remove();
                sum += val;
                queue.add(val);
            } else {
                count++;
                sum += val;
                queue.add(val);
            }
            return (double)(sum)/(double)(count);
        }
    }
    

  • 0
    X

    Thanks for sharing. It can be improved by below code, and no need the count, as it can be replaced by queue.size()

    class MovingAverage {
    
        /**
         * Initialize your data structure here.
         */
        Queue<Integer> queue = new LinkedList();
        int size;
        int sum;
    
        public MovingAverage(int size) {
            this.size = size;
        }
    
        public double next(int val) {
            if (queue.size() == size) {
                sum -= queue.remove();
            }
            sum += val;
            queue.add(val);
            return (double) sum / queue.size();
        }
    }
    

Log in to reply
 

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