LeetCode 346. Moving Average from Data Stream

原题链接在这里:https://leetcode.com/problems/moving-average-from-data-stream/

题目:

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

题解:

维护一个queue, 当queue的size已经等于size时若是继续加新的val就需要poll值.

Time Complexity: MovingAverage(size) O(1), next(val) O(1).

Space: O(size) 需要维护queue

AC Java:

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

 

posted @ 2016-12-15 16:04  Dylan_Java_NYC  阅读(407)  评论(0编辑  收藏  举报