642. moving average from data stream

code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33

public class {
private int size;
private Queue<Integer> queue;
private double sum;

/*
* @param size: An integer
*/public (int size) {
// do intialization if necessary
this.queue = new LinkedList<Integer>();
this.size = size;
this.sum = 0;
}

/*
* @param val: An integer
* @return:
*/
public double next(int val) {
// write your code here
sum += val;
queue.offer(val);
if (queue.size() > size) {
sum = sum - queue.poll();

}
return sum / queue.size();
// 怎么把元素取出来,按原先的顺序放进去?
//不需要这样,只要维持一个sum就好

}
}