Leetcode 346 Solution

This article provides solution to leetcode question 346 (moving-average-from-data-stream)

https://leetcode.com/problems/moving-average-from-data-stream

Solution

class MovingAverage { deque<int> q; int64_t m_sum; int m_size;
public: /** Initialize your data structure here. */ MovingAverage(int size) { m_size = size; m_sum = 0; }
double next(int val) { m_sum += val; q.push_back(val);
if (q.size() > m_size) { m_sum -= q.front(); q.pop_front(); }
return m_sum * 1.0 / q.size(); } };
/** * Your MovingAverage object will be instantiated and called as such: * MovingAverage obj = new MovingAverage(size); * double param_1 = obj.next(val); */