Leetcode 346 Moving Average from Data Stream
2017-01-10 06:54
295 查看
Given a stream of integers and a window size, calculate the moving average of all integers in the sliding window.
For example,
首先这是一个Window的问题,要注意window满了之后每次都会替换最老的那一个元素
public class MovingAverage {
private int[] window;
private int insert,n;
private long sum;
/** Initialize your data structure here. */
public MovingAverage(int size) {
window = new int[size];
insert = 0;//insert代表的就是下一个要被替换的元素的位置
sum = 0;
}
public double next(int val) {
if (n < window.length) n++;
sum -= window[insert];
sum += val;
window[insert] = val;
insert = (insert + 1) % window.length;//insert的数值变化分别为0,1,2,0,1,2.。。。。
return (double)sum / n;
}
}
/**
* Your MovingAverage object will be instantiated and called as such:
* MovingAverage obj = new MovingAverage(size);
* double param_1 = obj.next(val);
*/
不一定就要让window进行移动,可以按照012012012.。。的顺序进行替换
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
首先这是一个Window的问题,要注意window满了之后每次都会替换最老的那一个元素
public class MovingAverage {
private int[] window;
private int insert,n;
private long sum;
/** Initialize your data structure here. */
public MovingAverage(int size) {
window = new int[size];
insert = 0;//insert代表的就是下一个要被替换的元素的位置
sum = 0;
}
public double next(int val) {
if (n < window.length) n++;
sum -= window[insert];
sum += val;
window[insert] = val;
insert = (insert + 1) % window.length;//insert的数值变化分别为0,1,2,0,1,2.。。。。
return (double)sum / n;
}
}
/**
* Your MovingAverage object will be instantiated and called as such:
* MovingAverage obj = new MovingAverage(size);
* double param_1 = obj.next(val);
*/
不一定就要让window进行移动,可以按照012012012.。。的顺序进行替换
相关文章推荐
- Leetcode Everyday: 346. Moving Average from Data Stream
- [Leetcode] 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 Moving Average from Data Stream
- Leetcode: Moving Average from Data Stream
- 346. Moving Average from Data Stream
- 346. Moving Average from Data Stream
- [LeetCode] Moving Average from Data Stream 从数据流中移动平均值
- 346. Moving Average from Data Stream
- Moving Average from Data Stream
- Moving Average from Data Stream
- Moving Average from Data Stream
- Moving Average from Data Stream
- Moving Average from Data Stream
- Moving Average from Data Stream
- [LeetCode][Java]Find Median from Data Stream
- leetcode笔记:Find Median from Data Stream