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

 

posted @ 2016-08-13 10:56  fenshen371  阅读(130)  评论(0编辑  收藏  举报