您的位置:首页 > 其它

LeetCode 346. Moving Average from Data Stream(数据流移动平均值)

2016-05-01 06:23 344 查看
原题网址:https://leetcode.com/problems/moving-average-from-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

方法:使用双端链表保持窗口内的数值。

public class MovingAverage {
private LinkedList<Integer> dequeue = new LinkedList<>();
private int size;
private long sum;

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

public double next(int val) {
if (dequeue.size() == size) sum -= dequeue.removeFirst();
dequeue.addLast(val);
sum += val;
// System.out.printf("size=%d, val=%d, dequeue=%s, sum=%d\n", size, val, dequeue, sum);
return (double)sum / dequeue.size();
}
}

/**
* Your MovingAverage object will be instantiated and called as such:
* MovingAverage obj = new MovingAverage(size);
* double param_1 = obj.next(val);
*/


另一种实现:

public class MovingAverage {
private int[] vals;
private int from, size;
private long sum;

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

public double next(int val) {
if (size < vals.length) {
sum += val;
vals[size++] = val;
} else {
sum -= vals[from];
vals[from] = val;
from = (from+1) % vals.length;
}
return (double)sum / size;
}
}

/**
* Your MovingAverage object will be instantiated and called as such:
* MovingAverage obj = new MovingAverage(size);
* double param_1 = obj.next(val);
*/
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: