給定一個整數數據流和一個窗口大小,根據該滑動窗口的大小,計算其所有整數的移動平均值。
示例:
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
思路:一個隊列記錄數字,用一個變量記錄窗口和即可,每次更新窗口和。
?
class MovingAverage {int size//窗口大小int windowSum = 0//窗口和int count = 0;//添加數字的次數Deque queue = new ArrayDeque<Integer>();public MovingAverage(int size) {this.size = size;}public double next(int val) {++count;// calculate the new sum by shifting the windowqueue.add(val);//看有沒有過期的數字(最左邊)int tail = count > size ? (int)queue.poll() : 0;//更新窗口和windowSum = windowSum - tail + val;return windowSum * 1.0 / Math.min(size, count);}
}
/*** Your MovingAverage object will be instantiated and called as such:* MovingAverage obj = new MovingAverage(size);* double param_1 = obj.next(val);*/
?