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

29 篇文章 0 订阅
12 篇文章 0 订阅

原题网址: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);
 */


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值