Moving Average from Data Stream -- LeetCode

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  */

 

转载于:https://www.cnblogs.com/fenshen371/p/5767544.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值