lifeiteng

346. Moving Average from Data Stream

Sep 11th, 2018
64
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 0.62 KB | None | 0 0
  1. class MovingAverage {
  2.  
  3.     /** Initialize your data structure here. */
  4.     int[] ary = new int[0];
  5.     int cursize = 0, sum = 0, pos = 0;
  6.     public MovingAverage(int size) {
  7.         ary = new int[size];
  8.     }
  9.    
  10.     public double next(int val) {
  11.         if(cursize < ary.length) cursize++;
  12.         sum -= ary[pos];
  13.         sum += val;
  14.         ary[pos] = val;
  15.         pos = (pos + 1) % ary.length;
  16.         return (double) sum / cursize;
  17.     }
  18. }
  19.  
  20. /**
  21.  * Your MovingAverage object will be instantiated and called as such:
  22.  * MovingAverage obj = new MovingAverage(size);
  23.  * double param_1 = obj.next(val);
  24.  */
Add Comment
Please, Sign In to add comment