C++ with std::list


  • 0
    E

    Using std::list class (I like the API better than std::queue) for keeping the running window and for O(1) inserts and deletes when we update that window. Whether std::list::size() is O(1) or O(n) seems to be undefined but if it is not we can keep a instance variable of the current window size. Got a runtime of 42ms.

    This is my first LeetCode problem so let me know how I can optimize even further. Peace.

    class MovingAverage {
        list<int> _window;
        int _size;
        int _sum = 0;
    public:
        MovingAverage(int size) : _size(size) {}
        double next(int val) {
            if (_window.size() < _size) {
                _window.push_back(val);
                _sum += val; 
            } else {
                _sum -= _window.front();
                _window.pop_front();
                _sum += val;
                _window.push_back(val);
            }
            return (double)_sum / _window.size();
        }
    };```

Log in to reply
 

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