码迷,mamicode.com
首页 > 其他好文 > 详细

Moving Average from Data Stream

时间:2016-07-01 06:45:52      阅读:249      评论:0      收藏:0      [点我收藏+]

标签:

 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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!