Shawngbk / Leecode

Questions of Leecode
0 stars 0 forks source link

346. Moving Average from Data Stream #120

Open Shawngbk opened 7 years ago

Shawngbk commented 7 years ago

list元素少于size,则把当前val加入到list,作为下次运算使用

public class MovingAverage { private Queue list = new LinkedList(); private int size; private int sum;

/** Initialize your data structure here. */
public MovingAverage(int size) {
    this.size = size;
}

public double next(int val) {
    double res = 0;
    if(list.size() < size) {
        sum = sum + val;
        list.offer(val);
        res = (double)sum/list.size();
    } else {
        sum = sum - list.poll();
        sum = sum + val;
        list.offer(val);
        res = (double)sum/list.size();
    }
    return res;
}

}

/**

Shawngbk commented 7 years ago

google