Easy to Understand Solution in C++


  • 0
    F
    class MovingAverage {
    public:
        /** Initialize your data structure here. */
        MovingAverage(int size) {
            currentSum_ = 0;
            size_ = size;
        }
        
        double next(int val) {
            if (window_.size() == size_) {
                currentSum_ -= window_.front();
                window_.pop_front();
            }
            currentSum_ += val;
            window_.push_back(val);
    
            return (currentSum_ / (double)window_.size());
        }
    private:
        int       currentSum_;
        int       size_;
        list<int> window_;
    };
    

Log in to reply
 

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