LeetCode 346. Moving Average from Data Stream(数据流移动平均值)
2016-05-01 06:23
344 查看
原题网址: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,
方法:使用双端链表保持窗口内的数值。
另一种实现:
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
方法:使用双端链表保持窗口内的数值。
public class MovingAverage { private LinkedList<Integer> dequeue = new LinkedList<>(); private int size; private long sum; /** Initialize your data structure here. */ public MovingAverage(int size) { this.size = size; } public double next(int val) { if (dequeue.size() == size) sum -= dequeue.removeFirst(); dequeue.addLast(val); sum += val; // System.out.printf("size=%d, val=%d, dequeue=%s, sum=%d\n", size, val, dequeue, sum); return (double)sum / dequeue.size(); } } /** * Your MovingAverage object will be instantiated and called as such: * MovingAverage obj = new MovingAverage(size); * double param_1 = obj.next(val); */
另一种实现:
public class MovingAverage { private int[] vals; private int from, size; private long sum; /** Initialize your data structure here. */ public MovingAverage(int size) { this.vals = new int[size]; } public double next(int val) { if (size < vals.length) { sum += val; vals[size++] = val; } else { sum -= vals[from]; vals[from] = val; from = (from+1) % vals.length; } return (double)sum / size; } } /** * Your MovingAverage object will be instantiated and called as such: * MovingAverage obj = new MovingAverage(size); * double param_1 = obj.next(val); */
相关文章推荐
- git log
- LeetCode 334. Increasing Triplet Subsequence
- 04- Shell脚本学习--条件控制和循环语句
- LeetCode 008 String to Integer (atoi)
- HTTP客户端识别与cookie机制
- reverse a string反转字符串
- [LeetCode] Moving Average from Data Stream 从数据流中移动平均值
- Causing exception while using AlertDialog
- 数据库设计中实体关联的四种类型
- LeetCode 007 Reverse Integer
- 回溯法 -数据结构与算法
- 回溯法 -数据结构与算法
- 二叉树遍历 - 数据结构
- 二叉树遍历 - 数据结构
- 数据结构- 串的模式匹配算法:BF和 KMP算法
- 数据结构-栈和队列
- 数据结构- 串的模式匹配算法:BF和 KMP算法
- 数据结构-栈和队列
- 数据结构-线性表
- 数据结构-线性表