346. Moving Average from Data Stream

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/u012033124/article/details/79327309

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

题目大意:初始化一个滑动窗口,大小为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);
 */
阅读更多
换一批

没有更多推荐了,返回首页