C++_using Queue


  • 0
    class MovingAverage {
    int count = 0;
    int sum = 0;
    queue<int> q;
    public:
    /** Initialize your data structure here. */
    MovingAverage(int size) {
        count = size;
    }
    
    double next(int val) {
        if(q.size() < count){
            q.push(val);
            sum += val;
            return sum/(q.size() * 1.0);
        }else{
            sum = sum - q.front() + val;
            q.pop();
            q.push(val);
            return sum/(count * 1.0);
        }
    }
    };

Log in to reply
 

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