- 346. Moving Average from Data St
- 346. Moving Average from Data St
- 346. Moving Average from Data St
- 2018-10-18 Moving Average from D
- leetcode 346. Moving Average fro
- [10.16 Easy] 346. Moving Average
- mapped states of consciousness
- 使用python构建ARIMA模型进行预测分析的小说明:fore
- Group-Normalization-Tensorflow-测
- MACD指标——指数平滑异同平均线(一)
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
Solution:
思路:
Time Complexity: O(N) Space Complexity: O(N)
Solution Code:
public class MovingAverage {
private int [] window;
private int n, insert;
private long sum;
/** Initialize your data structure here. */
public MovingAverage(int size) {
window = new int[size];
insert = 0;
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;
return (double)sum / n;
}
}
网友评论