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);
*/
算是簡(jiǎn)答題吧。但也是慚愧舆绎。一開(kāi)始想到的是用 ArrayList來(lái)做鲤脏。。吕朵。
豬嗎猎醇,那空間開(kāi)銷(xiāo)多大啊。努溃。硫嘶。
然后點(diǎn) tag,發(fā)現(xiàn)用Queue, 一下子明白了梧税。
Anyway, Good luck, Richardo! -- 09/12/2016