C++ solution using Queue


  • 0
    M
    class MovingAverage {
    public:
        /** Initialize your data structure here. */
        MovingAverage(int size) {
           mySize = size;
           myAverage = 0;
        }
        
        double next(int val) {
            if(myQueue.size() < mySize){
                myQueue.push(val);
                myAverage = (myAverage * (myQueue.size() - 1) + val) / myQueue.size();
                return myAverage;
            }else{
                myQueue.push(val);
                myAverage = (myAverage * mySize - myQueue.front() + val) / mySize;
                myQueue.pop();
                return myAverage;
            }
        }
    private:
        std::queue<int> myQueue;
        int mySize;
        double myAverage;
    };
    
    /**
     * 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.