leetcode 解题思路

FLAG必经之路

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

思路:用queue,注意queue的使用方式是linkedlist

注意:计算的queue sum的时候,用for循环,不需要poll出来,否则计算错误。

public class MovingAverage {


    /** Initialize your data structure here. */
    private int size = 0;
    private Queue<Integer> queue;
    public MovingAverage(int size) {
        this.size = size;
        queue = new LinkedList<Integer>();
    }
    
    public double next(int val) {
        if(queue.size() >= this.size){
            queue.poll();
            queue.offer(val);
        } else {
            queue.offer(val);
        }
        double sum = 0;
        for(Integer i: queue){
            sum += i;
        }
        return sum/queue.size();
    }
}


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


阅读更多
版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/u013325815/article/details/51782229
个人分类: PriorityQueue
想对作者说点什么? 我来说一句

exp moving average的matlab代码

2014年09月09日 520B 下载

没有更多推荐了,返回首页

加入CSDN,享受更精准的内容推荐,与500万程序员共同成长!
关闭
关闭