Given a stream of integers and a window size, calculate the moving average of all integers in the sliding window.
Example:
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
這道題定義了一個MovingAverage類,里面可以存固定個數字,然后我們每次讀入一個數字,如果加上這個數字后總個數大於限制的個數,那么我們移除最早進入的數字,然后返回更新后的平均數,這種先進先出的特性最適合使用隊列queue來做,而且我們還需要一個double型的變量sum來記錄當前所有數字之和,這樣有新數字進入后,如果沒有超出限制個數,則sum加上這個數字,如果超出了,那么sum先減去最早的數字,再加上這個數字,然后返回sum除以queue的個數即可:
class MovingAverage { public: MovingAverage(int size) { this->size = size; sum = 0; } double next(int val) { if (q.size() >= size) { sum -= q.front(); q.pop(); } q.push(val); sum += val; return sum / q.size(); } private: queue<int> q; int size; double sum; };
類似題目:
https://leetcode.com/problems/moving-average-from-data-stream/