Tuesday, October 6, 2020

346. Moving Average from Data Stream -----E

Given a stream of integers and a window size, calculate the moving average of all integers in the sliding window.

Example:

MovingAverage m = new MovingAverage(3);
m.next(1) = 1
m.next(10) = (1 + 10) / 2
m.next(3) = (1 + 10 + 3) / 3 

m.next(5) = (10 + 3 + 5) / 3 


A:

class MovingAverage {
public:
    /** Initialize your data structure here. */
    MovingAverage(int size) {
        m_size = size;
        total = 0;
    }
    
    double next(int val) {
        if(DQ.size() == m_size){
            total -= DQ.front();
            DQ.pop_front();
        }
        DQ.push_back(val);
        total += val;
        return total/ DQ.size();
    }
private:
    deque<int> DQ;
    double total =0;
    int m_size;
};

/**
 * Your MovingAverage object will be instantiated and called as such:
 * MovingAverage* obj = new MovingAverage(size);
 * double param_1 = obj->next(val);
 */


No comments:

Post a Comment