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记录进入窗口的整数。当流进窗口的整数不足时,计算所有窗口内的数字和返回,当进入窗口的整数多于窗口大小时,移除最先进入窗口的整数,新的整数进入queue,然后计算窗口内的整数和。

Java:

public class MovingAverage {
private double previousSum = 0.0;
private int maxSize;
private Queue<Integer> currentWindow;
/** Initialize your data structure here. */
public MovingAverage(int size) {
currentWindow = new LinkedList<Integer>();
maxSize = size;
} public double next(int val) {
if(currentWindow.size()==maxSize){
previousSum -= currentWindow.remove();
}
currentWindow.add(val);
previousSum += val;
return previousSum/currentWindow.size();
}
} /**
* Your MovingAverage object will be instantiated and called as such:
* MovingAverage obj = new MovingAverage(size);
* double param_1 = obj.next(val);
*/  

Java:

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

Python:

# Time:  O(1)
# Space: O(w)
from collections import deque class MovingAverage(object):
def __init__(self, size):
"""
Initialize your data structure here.
:type size: int
"""
self.__size = size
self.__sum = 0
self.__q = deque([]) def next(self, val):
"""
:type val: int
:rtype: float
"""
if len(self.__q) == self.__size:
self.__sum -= self.__q.popleft()
self.__sum += val
self.__q.append(val)
return 1.0 * self.__sum / len(self.__q) # Your MovingAverage object will be instantiated and called as such:
# obj = MovingAverage(size)
# param_1 = obj.next(val)  

C++:

class MovingAverage {
public:
MovingAverage(int size) {
this->size = size;
sum = 0;
} double next(int val) {
if (q.size() >= size) {
sum -= q.front(); q.pop();
}
q.push(val);
sum += val;
return sum / q.size();
} private:
queue<int> q;
int size;
double sum;
};

  

All LeetCode Questions List 题目汇总

[LeetCode] 346. Moving Average from Data Stream 从数据流中移动平均值的更多相关文章

  1. [LeetCode] Moving Average from Data Stream 从数据流中移动平均值

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

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

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

  3. [leetcode]346. Moving Average from Data Stream滑动窗口平均值

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

  4. 346. Moving Average from Data Stream

    /* * 346. Moving Average from Data Stream * 2016-7-11 by Mingyang * 这里注意的就是(double) sum / count * su ...

  5. 【LeetCode】346. Moving Average from Data Stream 解题报告(C++)

    作者: 负雪明烛 id: fuxuemingzhu 个人博客:http://fuxuemingzhu.cn/ 目录 题目描述 题目大意 解题方法 队列 日期 题目地址:https://leetcode ...

  6. 346. Moving Average from Data Stream数据窗口流中位数的数据结构设计

    [抄题]: Given a stream of integers and a window size, calculate the moving average of all integers in ...

  7. LeetCode Moving Average from Data Stream

    原题链接在这里:https://leetcode.com/problems/moving-average-from-data-stream/ 题目: Given a stream of integer ...

  8. Moving Average from Data Stream -- LeetCode

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

  9. Moving Average from Data Stream

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

随机推荐

  1. PAT甲级1005水题飘过

    题目分析:用一个字符串输入之后遍历每一位求和后,不断%10获取最后一位存储下来,逆序用对应的英文单词输出(注意输入为0的情况) #include<iostream> #include< ...

  2. python笔记41-虚拟环境virtualenv

    前言 如果你是一个python初学者,我是不建议你搞python虚拟环境的,我看到很多python的初学者同学,使用最新版的pycharm,新建一个工程时候默认就是venu虚拟环境. 然后在使用cmd ...

  3. appium+python自动化63-使用Uiautomator2报错问题解决

    前言 appium desktop V1.7.1版本使用命令行版本启动appium后,使用Uiautomator2定位toast信息报错:appium-uiautomator2-server-v0.3 ...

  4. 在腾讯CentOS7.4云服务器上安装Docker,在Docker上安装配置MySQL、Tomcat和Nginx

    提示:以下是在腾讯CentOS7.4云服务器上操作. Docker的基本操作:https://www.cnblogs.com/opsprobe/p/10963098.html 一.安装Docker # ...

  5. 解决PHP处理图片时内存占用过高问题

    用过GD库的同学可能都知道,使用imagecreatetruecolor()函数创建一个真彩色的画布是第一步.但是,如果画布的宽高超过平常的宽高,会带来极大的内存消耗.比如,一个9600×4800的画 ...

  6. test20190925 老L

    100+0+0=100.概率题套路见的太少了,做题策略不是最优的. 排列 给出 n 个二元组,第 i 个二元组为(ai,bi). 将 n 个二元组按照一定顺序排成一列,可以得到一个排列.显然,这样的排 ...

  7. 启用Microsoft loopback Adapte

    开始▶控制面板▶系统   系统▶设备管理器   此时,点击操作的菜单是没有有用子菜单的,需要点击一下网络适配器.   再点击操作▶添加过时硬件   添加硬件向导▶下一步   安装我手动从列表选择的硬件 ...

  8. [Codeforces 1265E]Beautiful Mirrors

    Description 题库链接 一共有 \(n\) 个关卡,你初始在第一个关卡.通过第 \(i\) 个关卡的概率为 \(p_i\).每一轮你可以挑战一个关卡.若通过第 \(i\) 个关卡,则进入第 ...

  9. Centos7安装Hive2.3

    准备 1.hadoop已部署(若没有可以参考:Centos7安装Hadoop2.7),集群情况如下: hostname IP地址 部署规划 node1 172.20.0.4 NameNode.Data ...

  10. JS判断某变量是否为某数组中的一个值的3种方法

    1.正则表达式 js 中判断某个元素是否存在于某个 js 数组中,相当于 PHP 语言中的 in_array 函数. 1 Array.prototype.in_array = function (e) ...