C++ easy understand solution


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

Log in to reply
 

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