346. Moving Average from Data Stream (Easy)

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

For 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
Show Company Tags
Show Tags

Solution: queue

49ms

class MovingAverage {
public:
    /** Initialize your data structure here. */
    MovingAverage(int size): k(size), sum(0) {

    }

    double next(int val) {
        sum += val;
        nums.push(val);
        if (nums.size() > k) {
            sum -= nums.front();
            nums.pop();
        }
        return sum/nums.size();
    }
private:
    int k;
    double sum;
    queue<int> nums;
};

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

version: use vector

46ms

class MovingAverage {
public:
    /** Initialize your data structure here. */
    MovingAverage(int size): k(size), n(0), insert(0), sum(0), nums(size,0) {

    }

    double next(int val) {
        if (n < k) ++n;
        sum += val;
        sum -= nums[insert];
        nums[insert] = val;
        insert = (insert+1)%k;
        return sum/n;
    }
private:
    int k, n, insert;
    double sum;
    vector<int> nums;
};

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

results matching ""

    No results matching ""