346.数据流中的移动平均值

题目大意:初始化一个滑动窗口,大小为w,输入一系列数,求窗口内的平均数,窗口会向前滑动,当窗口填满时,将最早进入的数弹出,加入新的数.

解题思路:用队列,求和时可以利用上次的和,不用每次从头到尾求

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);
 */

最后更新于