346. Moving Average from Data Stream

https://leetcode.com/problems/moving-average-from-data-stream/description/

The main idea of ​​the title: Initialize a sliding window, the size is w, enter a series of numbers, find the average number in the window, the window will slide forward, when the window is full, the earliest entered number will be popped up, and new numbers will be added.
Solve the problem Idea: Using a queue, you can use the last sum when summing, instead of searching from the beginning to the end every time.
Code :

class MovingAverage {
public:
    /** Initialize your data structure here. */
    MovingAverage(int size) {
        q_size = size;
        sum = 0;
    }

    double next(int val) {
        double res;
        if (q.size() < q_size) {  //当队列未达上限
            q.push(val);
            sum += val;  //利用上次求和结果
        } else {  //当队列达上限
            //减头
            sum -= q.front();  
            q.pop();
            //加尾
            q.push(val);
            sum += val;  
        }
        res = (double)sum / q.size();
        return res;
    }
private:
    queue<int> q;  //队列.模拟滑动窗口
    int q_size;  //队列上限
    int sum;  //暂存求和
};

/**
 * Your MovingAverage object will be instantiated and called as such:
 * MovingAverage obj = new MovingAverage(size);
 * double param_1 = obj.next(val);
 */

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325698644&siteId=291194637