[LeetCode] 346. Moving Average from Data Stream 從數據流中移動平均值


 

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/

 

LeetCode All in One 題目講解匯總(持續更新中...)


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM