Moving Average from Data Stream

Given a stream of integers and a window size, calculate the moving average of all integers in the sliding window.

For example,
MovingAverage m = new MovingAverage(3);
m.next(1) = 1
m.next(10) = (1 + 10) / 2
m.next(3) = (1 + 10 + 3) / 3
m.next(5) = (10 + 3 + 5) / 3

分析:

利用Queue先进先出的特点即可。

 public class MovingAverage {
Queue<Integer> q;
double sum = ;
int size; /** Initialize your data structure here. */
public MovingAverage(int s) {
q = new LinkedList();
size = s;
} public double next(int val) {
if (q.size() == size) {
sum = sum - q.poll();
}
q.offer(val);
sum += val;
return sum / q.size();
}
}
上一篇:[原创].NET 分布式架构开发实战之一 故事起源


下一篇:zstu.2512. Moving Tables(贪心)