Skip to content

Latest commit

 

History

History
executable file
·
42 lines (37 loc) · 963 Bytes

0346. Moving Average from Data Stream.md

File metadata and controls

executable file
·
42 lines (37 loc) · 963 Bytes

346. Moving Average from Data Stream, easy, locked

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

// 32ms, 93%
class MovingAverage {
private:
    double sums;
    int valSize;
    list<int> vals;
public:
    /** Initialize your data structure here. */
    MovingAverage(int size) {
        valSize = size;
        sums = 0;
    }
    
    double next(int val) {
        if (vals.size() >= valSize) {
            sums -= vals.front();
            vals.pop_front();
        }
        sums += val;
        vals.push_back(val);
        return sums/vals.size();
    }
};

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