您的位置:首页 > 其它

Leetcode Everyday: 346. Moving Average from Data Stream

2016-05-11 20:53 453 查看
https://leetcode.com/problems/moving-average-from-data-stream/

public class MovingAverage {

/** Initialize your data structure here. */
LinkedList<Integer> queue;
int size;
int total;
public MovingAverage(int size) {
queue = new LinkedList<Integer>();
this.size = size;
total = 0;
}

public double next(int val) {
if(queue.size()<size){
queue.add(val);
total+=val;
return (total+0.0)/queue.size();
}else{
total-=queue.remove(0);
queue.add(val);
total+=val;
return (total+0.0)/size;
}
}
}

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

Using LinkedList to maintain the data structure, keep track of the total value to improve the efficiency

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
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  leetcode