标签:
1 public class MovingAverage { 2 private double average; 3 private int[] data; 4 private int index; 5 6 /** Initialize your data structure here. */ 7 public MovingAverage(int size) { 8 data = new int[size]; 9 index = 0; 10 average = 0.0; 11 } 12 13 public double next(int val) { 14 if (index < data.length) { 15 data[index++] = val; 16 average = (average * (index - 1) + val) / index; 17 } else { 18 int old = data[index % data.length]; 19 data[index++ % data.length] = val; 20 average += (double)(val - old) / data.length; 21 } 22 return average; 23 } 24 } 25 26 /** 27 * Your MovingAverage object will be instantiated and called as such: 28 * MovingAverage obj = new MovingAverage(size); 29 * double param_1 = obj.next(val); 30 */
1. Be careful with index.
Moving Average from Data Stream
标签:
原文地址:http://www.cnblogs.com/shuashuashua/p/5631736.html