Moving Average from Data Stream
给一个steam和size, 求平均数. 用queue.
class MovingAverage {
/** Initialize your data structure here. */
Queue<Integer> q;
int size;
public MovingAverage(int size) {
q = new LinkedList<>();
this.size = size;
}
public double next(int val) {
if(q.size() < size) {
q.add(val);
int c = q.size();
int sum = 0;
for(int n : q)
sum += n;
return (double) sum / c;
}
else {
q.poll();
q.add(val);
int sum = 0;
for(int n : q)
sum += n;
return (double) sum / size;
}
}
}
/**
* Your MovingAverage object will be instantiated and called as such:
* MovingAverage obj = new MovingAverage(size);
* double param_1 = obj.next(val);
*/