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