Google – Moving Window
给一个Iterator和一个window size, 要求Wrap这个iterator来实现一个moving window class,在call next()的时候返回moving average。
[Solution]
Queue
这题就不需要考虑Iterator的那些Edge case。
Read full article from Google – Moving Window
给一个Iterator和一个window size, 要求Wrap这个iterator来实现一个moving window class,在call next()的时候返回moving average。
[Solution]
Queue
这题就不需要考虑Iterator的那些Edge case。
class MovingWindow implements Iterator<Double> { Iterator<Double> it; int window; Queue<Double> queue; double sum; public MovingWindow(Iterator<Double> it, int window) { this.it = it; this.window = window; this.queue = new LinkedList<>(); } @Override public boolean hasNext() { return it.hasNext(); } @Override public double next() { double curr = it.next(); queue.offer(curr); sum += curr; if (queue.size() > window) { sum -= queue.poll(); } return sum / window; }}