Simple Accepted Solution


  • 0
    D

    Lemme know how can be further improved.

    public class MovingAverage {
           int  outerSize=0;
            List<Integer> ls;
        /** Initialize your data structure here. */
        public MovingAverage(int size) {
            outerSize=size;
           ls = new ArrayList<Integer>();
        }
        
        public double next(int val) {
             ls.add(val);
             if(ls.size()>outerSize)
                   ls.remove(0);// remove 0 th
                    
                    
                   
                    int sum=0;
                   for(int n: ls)
                      sum+=n;
                      
                return (double)sum/ls.size();      
        }
    }

  • 0
    G

    Hey, you shouldn't iterate over your window over and over to get the sum, you can update it!
    Just substract from sum your oldest element and add the newest.


Log in to reply
 

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