Skip to content

Commit

Permalink
Create moving-average-from-data-stream.cpp
Browse files Browse the repository at this point in the history
  • Loading branch information
kamyu104 committed May 1, 2016
1 parent 7086d14 commit 2765474
Showing 1 changed file with 31 additions and 0 deletions.
31 changes: 31 additions & 0 deletions C++/moving-average-from-data-stream.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
// Time: O(1)
// Space: O(w)

class MovingAverage {
public:
/** Initialize your data structure here. */
MovingAverage(int size) : size_(size), sum_(0) {
}

double next(int val) {
if (q_.size() == size_) {
sum_ -= q_.front();
q_.pop();
}
q_.emplace(val);
sum_ += val;
return 1.0 * sum_ / q_.size();
}

private:
int size_;
int sum_;
queue<int> q_;
};

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

0 comments on commit 2765474

Please sign in to comment.