c++ vector Impl


  • 0
    T
    class MovingAverage {
        vector<int> elem;
        int ptr, sum, sz;
    public:
        /** Initialize your data structure here. */
        MovingAverage(int size):elem(vector<int>(size)), ptr(0), sum(0), sz(size) {
            
        }
        
        double next(int val) {
            sum += val;
            if (ptr >= sz) 
                sum -= elem[ptr%sz];
            elem[ptr++%sz] = val;
            return (double)sum / (double)min(ptr, sz);
        }
    };
    

Log in to reply
 

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