资讯专栏INFORMATION COLUMN

[LeetCode] 346. Moving Average from Data Stream

svtter / 1448人阅读

Problem

Given a stream of integers and a window size, calculate the moving average of all integers in the sliding window.

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

Solution
class MovingAverage {

    Queue queue;
    int size;
    int sum;
    /** Initialize your data structure here. */
    public MovingAverage(int size) {
        this.queue = new LinkedList<>();
        this.size = size;
        this.sum = 0;
    }
    
    public double next(int val) {
        if (queue.size() == size) {
            sum -= queue.poll();
        }
        queue.offer(val);
        sum += val;
        return (double) 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://www.ucloud.cn/yun/77381.html

相关文章

  • 科学计算与数据可视化1

    摘要:科学计算与数据可视化程序设计模块最重要的一个特点就是其维数组对象即该对象是一个快速而灵活的大数据集容器。两行及以上为二维表示数组各维度大小的元组。 科学计算与数据可视化1 @(程序设计) numpy模块 Numpy最重要的一个特点就是其N维数组对象(即ndarray)该对象是一个快速而灵活的大数据集容器。 使用Numpy,开发人员可以执行以下操作: 1、数组的算数和逻辑运算。 2、...

    aervon 评论0 收藏0
  • [LintCode/LeetCode] Sliding Window Maximum/Median

    摘要:窗口前进,删队首元素保证队列降序加入当前元素下标从开始,每一次循环都将队首元素加入结果数组 Sliding Window Maximum Problem Given an array of n integer with duplicate number, and a moving window(size k), move the window at each iteration fro...

    crelaber 评论0 收藏0
  • [LeetCode]Find Median from Data Stream

    Find Median from Data Stream Median is the middle value in an ordered integer list. If the size of the list is even, there is no middle value. So the median is the mean of the two middle value. Examp...

    suemi 评论0 收藏0
  • Node.js 指南(流中的背压)

    摘要:在数据缓冲区已超过或写入队列当前正忙的任何情况下,将返回。当返回值时,背压系统启动,它会暂停传入的流发送任何数据,并等待消费者再次准备就绪,清空数据缓冲区后,将发出事件并恢复传入的数据流。 流中的背压 在数据处理过程中会出现一个叫做背压的常见问题,它描述了数据传输过程中缓冲区后面数据的累积,当传输的接收端具有复杂的操作时,或者由于某种原因速度较慢时,来自传入源的数据就有累积的趋势,就像...

    Tony 评论0 收藏0

发表评论

0条评论

最新活动
阅读需要支付1元查看
<