Moving Average from Data Stream
2016-10-15 05:57
330 查看
Given a stream of integers and a window size, calculate the moving average of all integers in the sliding window.
For example,
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
1 class MovingAverage { 2 public: 3 /** Initialize your data structure here. */ 4 MovingAverage(int size) { 5 windowSize = size; 6 count = 0; 7 currentSum = 0; 8 } 9 10 double next(int val) { 11 value.push_back(val); 12 currentSum += val; 13 count++; 14 if (count > windowSize) { 15 currentSum -= value[count - 1 - windowSize]; 16 return currentSum / windowSize; 17 } 18 return currentSum / count; 19 } 20 private: 21 int windowSize; 22 int count; 23 double currentSum; 24 vector<int> value; 25 }; 26 27 /** 28 * Your MovingAverage object will be instantiated and called as such: 29 * MovingAverage obj = new MovingAverage(size); 30 * double param_1 = obj.next(val); 31 */
相关文章推荐
- Leetcode 346 Moving Average from Data Stream
- Moving Average from Data Stream
- 346. Moving Average from Data Stream
- 346. Moving Average from Data Stream
- 346. Moving Average from Data Stream
- [leetcode] 346. Moving Average from Data Stream 解题报告
- [LeetCode] 346. Moving Average from Data Stream 从数据流中移动平均值
- [Leetcode] 346. Moving Average from Data Stream 解题报告
- Leetcode Everyday: 346. Moving Average from Data Stream
- Moving Average from Data Stream
- Moving Average from Data Stream
- Moving Average from Data Stream -- LeetCode
- Leetcode: Moving Average from Data Stream
- [LeetCode] Moving Average from Data Stream 从数据流中移动平均值
- Moving Average from Data Stream
- Moving Average from Data Stream
- LeetCode Moving Average from Data Stream
- 346. Moving Average from Data Stream
- Find Median from Data Stream
- 295. Find Median from Data Stream【H】【2.7】