C++ 42ms solution with a trick


  • 0
    N

    It's quite self-explained.

    class MovingAverage {
    private:
        int window, count;
        double ave;
        queue<int> qu;
    public:
        /** Initialize your data structure here. */
        MovingAverage(int size) {
            window = size;
            count = 0;
            ave = 0;
        }
        
        double next(int val) {
            if(count < window){
                qu.push(val);
                count++;
                ave = (ave*(count-1)+val)/count;
                return ave;
            }
            else {
                int fr = qu.front();
                qu.pop();
                qu.push(val);
                ave= (ave*window - fr + val)/window;
                return ave;
            } 
                
        }
    };
    

Log in to reply
 

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