Moving Average from Data Stream
2017-01-03 06:49
281 查看
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先进先出的特点即可。
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先进先出的特点即可。
1 public class MovingAverage { 2 Queue<Integer> q; 3 double sum = 0; 4 int size; 5 6 /** Initialize your data structure here. */ 7 public MovingAverage(int s) { 8 q = new LinkedList(); 9 size = s; 10 } 11 12 public double next(int val) { 13 if (q.size() == size) { 14 sum = sum - q.poll(); 15 } 16 q.offer(val); 17 sum += val; 18 return sum / q.size(); 19 } 20 }
相关文章推荐
- 346. Moving Average from Data Stream
- 346. Moving Average from Data Stream
- 346. Moving Average from Data Stream
- [leetcode] 346. Moving Average from Data Stream 解题报告
- [LeetCode] 346. Moving Average from Data Stream 从数据流中移动平均值
- Moving Average from Data Stream
- [Leetcode] 346. Moving Average from Data Stream 解题报告
- Leetcode Everyday: 346. Moving Average from Data Stream
- Moving Average from Data Stream
- Moving Average from Data Stream -- LeetCode
- [LeetCode] Moving Average from Data Stream 从数据流中移动平均值
- Leetcode: Moving Average from Data Stream
- Moving Average from Data Stream
- Moving Average from Data Stream
- 346. Moving Average from Data Stream
- LeetCode Moving Average from Data Stream
- Leetcode 346 Moving Average from Data Stream
- Moving Average from Data Stream
- [转]Send a data stream from ABAP to UNIX named pipe
- [leetcode295]Find Median from Data Stream