From 2765474d9951d3230033d4a45169d40aca950c65 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 1 May 2016 19:41:04 +0800 Subject: [PATCH] Create moving-average-from-data-stream.cpp --- C++/moving-average-from-data-stream.cpp | 31 +++++++++++++++++++++++++ 1 file changed, 31 insertions(+) create mode 100644 C++/moving-average-from-data-stream.cpp diff --git a/C++/moving-average-from-data-stream.cpp b/C++/moving-average-from-data-stream.cpp new file mode 100644 index 000000000..e4ac8d76e --- /dev/null +++ b/C++/moving-average-from-data-stream.cpp @@ -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 q_; +}; + +/** + * Your MovingAverage object will be instantiated and called as such: + * MovingAverage obj = new MovingAverage(size); + * double param_1 = obj.next(val); + */ +