C++ clean and easy solution using queue


  • 0
    D
    class MovingAverage {
    public:
        /** Initialize your data structure here. */
        MovingAverage(int size) : size(size), sum(0) {}
        
        double next(int val) {
            if (q.size() == size) {
                sum -= q.front();
                q.pop();
            }
            q.push(val);
            sum += val;
            return sum / q.size();
        }
    private:
        queue<int> q;
        int size;
        double sum;
    };
    
    /**
     * Your MovingAverage object will be instantiated and called as such:
     * MovingAverage obj = new MovingAverage(size);
     * double param_1 = obj.next(val);
     */
    

Log in to reply
 

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