博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
LeetCode 346. Moving Average from Data Stream (数据流动中的移动平均值)$
阅读量:4694 次
发布时间:2019-06-09

本文共 1617 字,大约阅读时间需要 5 分钟。

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) = 1m.next(10) = (1 + 10) / 2m.next(3) = (1 + 10 + 3) / 3m.next(5) = (10 + 3 + 5) / 3

 


题目标签:Design

  这道题目让我们设计一个移动平均值的结构,我们有一个input size, 这个size是控制着我们的window。每次都新的数字进来,如果目前的size小于window,那么继续加入。如果新的数字进来,size已经满了,等于window size。那么我们需要把第一个数字去除,然后加入新的数字。可以利用ArrayList来模仿queue实现,add 加入到最后, remove(0) 把第一个数字去除。还要设一个sum, 每次加入,就加入sum, 当满了之后,每次去除,只要从sum里减去。这样就可以避免每一次加入一个数字的时候,都要遍历一次queue来得到所有数字之和。

 

Java Solution:

Runtime beats 71.48% 

完成日期:07/09/2017

关键词:Design

关键点:利用ArrayList来模仿Queue

 

1 public class MovingAverage { 2  3     ArrayList
queue; 4 int queue_size; 5 double sum; 6 /** Initialize your data structure here. */ 7 public MovingAverage(int size) 8 { 9 queue = new ArrayList<>(size);10 queue_size = size;11 sum = 0;12 }13 14 public double next(int val) 15 {16 if(queue.size() == queue_size) // meaning it is full17 {18 sum -= queue.get(0); // minus head19 queue.remove(0); // remove the head20 }21 22 queue.add(val); //append the new integer23 sum += val; // add into sum24 25 return (sum / queue.size()); 26 }27 }28 29 /**30 * Your MovingAverage object will be instantiated and called as such:31 * MovingAverage obj = new MovingAverage(size);32 * double param_1 = obj.next(val);33 */

参考资料:N/A

 

LeetCode 算法题目列表 - 

转载于:https://www.cnblogs.com/jimmycheng/p/7144032.html

你可能感兴趣的文章
幻灯片的实现
查看>>
Eclipse Mars.1 (4.5.1) 发布下载转摘
查看>>
HDU 3863 (博弈) No Gambling
查看>>
文件锁使用
查看>>
iOS 中的加密方式
查看>>
pdftk
查看>>
OS_EVENT 信号量
查看>>
学习ThreadLocal
查看>>
在 Visual Studio 调试器中指定符号 (.pdb) 和源文件
查看>>
直接量
查看>>
leetcode 115. 不同的子序列(Distinct Subsequences)
查看>>
三元表达式
查看>>
Go初接触之libjpeg-turbo
查看>>
python--生成器协程运算
查看>>
php中文字符串截取乱码问题解决
查看>>
INFT 3030 Concurrent Programming
查看>>
小心了,这个设置会导致你的vm重启时被强制重装系统!
查看>>
邮票面值设计 (动态规划+DFS)
查看>>
解决INSTALL_FAILED_MISSING_SHARED_LIBRARY (转载)
查看>>
Linux内核高端内存
查看>>