Without any data structure simple java solution


  • -2
    S

    This one clocks 183ms

    public class MovingAverage {
        private int count = 0;
      	private int s;
      	private double sum = 0;
      	private boolean isFull = false;
      	private int first;
        /** Initialize your data structure here. */
        public MovingAverage(int size) {
            s = size;
        }
        
        public double next(int val) {
            if(count == s)
            {
                count = 0;
                isFull = true;
                
            }
         if(isFull) sum -= first;
         if(count == 0) first = val;
            count++;
            sum += val;
            return  (!isFull)? sum/count: sum/s;
        }
    }
    

    with array clocks 170ms but takes up all that space though

    public class MovingAverage {
        private int[] a;
        private int count;
      	private int s;
      	private double sum;
      	private boolean isFull;
        /** Initialize your data structure here. */
        public MovingAverage(int size) {
            a = new int[size];
            s = size;
            count = 0;
            sum = 0;
        }
        
        public double next(int val) {
            if(count == s)
            {
                count = 0;
                isFull = true;
                
            }
        int temp = (isFull)? a[count] : 0;
            a[count] = val;
            count++;
            sum += val - temp;
            double avg = (!isFull)? sum/count: sum/s ;
            return avg;
        }
    }

  • 1

    I don't get how the first one can work, honestly. I implemented it in Python and doesn't work.


Log in to reply
 

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