Friday, July 15, 2016

346. Moving Average from Data Stream

A typical application for queue. When queue is not full, we keep pushing the new number to the queue and compute the sum. When the queue is full, we subtract the front from the sum, pop out the front, push the new number to the end and add the new number to the sum.

1:  class MovingAverage {  
2:  private:  
3:    queue<int> que;  
4:    int m_size;  
5:    int sum;  
6:  public:  
7:    /** Initialize your data structure here. */  
8:    MovingAverage(int size) {  
9:      m_size = size;  
10:      sum = 0;  
11:    }  
12:    double next(int val) {  
13:      if (que.size() != m_size) {  
14:        que.push(val);  
15:        sum += val;  
16:      } else {  
17:        sum -= que.front();  
18:        que.pop();  
19:        que.push(val);  
20:        sum += val;  
21:      }  
22:      return sum * 1.0 / que.size();  
23:    }  
24:  };  
25:  /**  
26:   * Your MovingAverage object will be instantiated and called as such:  
27:   * MovingAverage obj = new MovingAverage(size);  
28:   * double param_1 = obj.next(val);  
29:   */  

No comments:

Post a Comment