forked from shuboc/LeetCode-2
-
Notifications
You must be signed in to change notification settings - Fork 1
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Create moving-average-from-data-stream.cpp
- Loading branch information
Showing
1 changed file
with
31 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); | ||
*/ | ||
|