The trials of the road LeetCode (3): moving average (346) the data stream

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

To a stream of integers and a window, calculating an average in a given size window numbers.

solution:

Thinking this question:
LinkedList.remove () method of the first value in the list for taking out and remove it.
Function similar Queue.poll () first branch taken queue, and removed from the queue

Each time a new value passed in time to determine whether the number is equal to the maximum number list, and if so, you will need to remove the front of a value from the list, and then stuffed the new value, and then use the sum of all values ​​divided by the current list of worthy number, the average value obtained in the current window number.

//保存当前窗口数字的总和
private double previousSum = 0.0;
//窗口的最大值
private int maxSize;
//链表用于保存当前窗口的值
private Queue<Integer> currentWindow;

public MovingAverage(int val){
    currentWindow = new LinkedList<Integer>();
    maxSize = val;
}

private double next(int val){
    double sum = 0;
    if(maxSize==currentWindow.size()){
        previousSum -= currentWindow.remove();
    }
    currentWindow.add(val);
    previousSum +=val;
    return previousSum/currentWindow.size();
}

Guess you like

Origin www.cnblogs.com/yaphse-19/p/12026735.html