Share my short code beating 96%


  • 1

    Use a variable to remember sum, not the avg, will get a better efficiency.

        Queue<Integer> q;
        int size;
        double avg;
        public MovingAverage(int size) {
            q = new LinkedList<>();
            this.size = size;
            avg=0.0;
        }
        
        public double next(int val) {
            if(q.size()==size)
                avg-=q.poll();
            q.offer(val);
            avg+=val;
            return avg/q.size();
        }
    

Log in to reply
 

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