---
# System prepended metadata

title: 0346. Moving Average from Data Stream
tags: [Leetcode, FaceBook, Easy, Medium]

---

# 0346. Moving Average from Data Stream
###### tags: `Leetcode` `Easy` `FaceBook` `Medium`
Link: https://leetcode.com/problems/moving-average-from-data-stream/

## 思路
可以动态维护一个arr，如果填满了，就再从头开始添
也可以用queue
## Code
Array 实现
```java=
class MovingAverage {
    int[] arr;
    int idx;
    int total;
    int size;
    boolean fill = false;
    public MovingAverage(int size) {
        arr = new int[size];
        idx = 0;
        total = 0;
        this.size = size;
    }
    
    public double next(int val) {
        if(idx == size){
            fill = true;
            idx = 0;
        }
        total -= arr[idx];
        arr[idx] = val;
        total += val;
        idx++;
        if(fill) return (double) total/size;
        else return (double) total/idx;
    }
}

```
Queue实现
```java=
class MovingAverage {
    int total;
    int count;
    int size;
    Queue<Integer> q;
    public MovingAverage(int size) {
        q = new LinkedList<Integer>();
        count = 0;
        total = 0;
        this.size = size;
    }
    
    public double next(int val) {
        int pop = 0;
        count++;
        if(q.size() == size){
            pop = q.poll();
        }
        q.offer(val);
        total = total-pop+val;
        return total*1.0/Math.min(count, size);
    }
}

```