码迷,mamicode.com
首页 > 其他好文 > 详细

Moving Average from Data Stream -- LeetCode

时间:2016-08-13 11:23:08      阅读:180      评论:0      收藏:0      [点我收藏+]

标签:

Given a stream of integers and a window size, calculate the moving average of all integers in the sliding window.

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 private:
 3     queue<int> numsInWindow;
 4     int windowSize;
 5     double lastAverage;
 6 public:
 7     /** Initialize your data structure here. */
 8     MovingAverage(int size) {
 9         windowSize = size;
10     }
11     
12     double next(int val) {
13         if (numsInWindow.empty()) {
14             numsInWindow.push(val);
15             lastAverage = (double) val;
16         }
17         else if (numsInWindow.size() < windowSize) {
18             double total = lastAverage * numsInWindow.size();
19             numsInWindow.push(val);
20             lastAverage = (total + val) / numsInWindow.size();
21         }
22         else {
23             double total = lastAverage * numsInWindow.size();
24             total -= numsInWindow.front();
25             numsInWindow.pop();
26             numsInWindow.push(val);
27             lastAverage = (total + val) / numsInWindow.size();
28         }
29         return lastAverage;
30     }
31 };
32 
33 /**
34  * Your MovingAverage object will be instantiated and called as such:
35  * MovingAverage obj = new MovingAverage(size);
36  * double param_1 = obj.next(val);
37  */

 

Moving Average from Data Stream -- LeetCode

标签:

原文地址:http://www.cnblogs.com/fenshen371/p/5767544.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!