C++ solution


  • 1
    class MovingAverage {
        int window=0;
        queue<int> q;
        int sum = 0;
    public:
        /** Initialize your data structure here. */
        MovingAverage(int size) {
            window = size;
        }
        
        double next(int val) {
            if(q.size() == window)
            {
                sum-=q.front();
                q.pop();
            }
            q.push(val);
            sum+=val;
            return sum*1.0/q.size();
        }
    };

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.