题目来源:
leetcode题目,网址:LCR 041. 数据流中的移动平均值 - 力扣(LeetCode)
解题思路:
使用队列保存最多 size 个元素然后计算平均值并返回即可。
解题代码:
- class MovingAverage {
- Queue<Integer> queue=new LinkedList<>();
- int maxSize=0;
- int sum=0;
- /** Initialize your data structure here. */
- public MovingAverage(int size) {
- this.maxSize=size;
- }
-
- public double next(int val) {
- if(queue.size()>=this.maxSize){
- this.sum-=queue.poll();
- }
- this.sum+=val;
- queue.offer(val);
- return (sum+0.0)/queue.size();
- }
- }
-
- /**
- * Your MovingAverage object will be instantiated and called as such:
- * MovingAverage obj = new MovingAverage(size);
- * double param_1 = obj.next(val);
- */
总结:
刚开始没明白题目什么意思,看官方题解后才理解。