My code:
public class MovingAverage {
Queue<Integer> q = new LinkedList<Integer>();
int size = 0;
int sum = 0;
/** Initialize your data structure here. */
public MovingAverage(int size) {
this.size = size;
}
public double next(int val) {
if (q.size() < size) {
q.offer(val);
sum += val;
return sum / (q.size() * 1.0);
}
else {
Integer out = q.poll();
sum -= out;
sum += val;
q.offer(val);
return sum / (q.size() * 1.0);
}
}
}
/**
* Your MovingAverage object will be instantiated and called as such:
* MovingAverage obj = new MovingAverage(size);
* double param_1 = obj.next(val);
*/
算是简答题吧。但也是惭愧。一开始想到的是用 ArrayList来做。。。
猪吗,那空间开销多大啊。。。
然后点 tag,发现用Queue, 一下子明白了。
Anyway, Good luck, Richardo! — 09/12/2016