[LeetCode] Moving Average from Data Stream 從資料流中移動平均值
阿新 • • 發佈:2018-12-27
Given a stream of integers and a window size, calculate the moving average of all integers in the sliding window.
For 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; returnsum / q.size(); } private: queue<int> q; int size; double sum; };