java面试题(9)

来源:互联网 发布:oracle sql 去掉重复 编辑:程序博客网 时间:2024/06/11 18:14

原题:

// 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/** * Your MovingAverage object will be instantiated and called as such: * MovingAverage obj = new MovingAverage(size); * double param_1 = obj.next(val); */

解析:窗口移动求平均值,移动大小自己定义
答案:

public class MovingAverage {    double previousSum = 0.0;    int maxSize;    Queue<Integer> window;    /** Initialize your data structure here. */    public MovingAverage(int size) {        this.maxSize = size;        window = new LinkedList<Integer>();    }    public double next(int val) {        if(window.size() == maxSize) {            previousSum -= window.remove();//如果已经是最大值,则队列去除第一个元素        }        window.add(val);        previousSum += val;        return previousSum / window.size();    }}

核心流程:利用队列,如果已经是最大值,则加入新值时,去除原先的数值

原创粉丝点击