https://leetcode.com/problems/moving-average-from-data-stream/
public class MovingAverage {
/** Initialize your data structure here. */
LinkedList<Integer> queue;
int size;
int total;
public MovingAverage(int size) {
queue = new LinkedList<Integer>();
this.size = size;
total = 0;
}
public double next(int val) {
if(queue.size()<size){
queue.add(val);
total+=val;
return (total+0.0)/queue.size();
}else{
total-=queue.remove(0);
queue.add(val);
total+=val;
return (total+0.0)/size;
}
}
}
/**
* Your MovingAverage object will be instantiated and called as such:
* MovingAverage obj = new MovingAverage(size);
* double param_1 = obj.next(val);
*/
Using LinkedList to maintain the data structure, keep track of the total value to improve the efficiency
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
本文介绍了如何使用LinkedList来优化数据结构,提高计算滑动窗口内的移动平均值的效率。通过实例展示了计算过程,并提供了一个实现类MovingAverage,实现了在数据流中动态计算移动平均值的功能。

被折叠的 条评论
为什么被折叠?



