Moving Average from Data Stream

Posted keepshuatishuati

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Moving Average from Data Stream相关的知识,希望对你有一定的参考价值。

 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的主要内容,如果未能解决你的问题,请参考以下文章

Moving Average from Data Stream

346. Moving Average from Data Stream - Easy

Leetcode 346. Moving Average from Data Stream

[leetcode]Moving Average from Data Stream

LeetCode-Moving Average from Data Stream

[LeetCode] 346. Moving Average from Data Stream ??????????????????????????????