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. linux卸载及安装mysql 5.7以上

    删除: 1.rpm -qa|grep -i mysql     查看安装的mysql 2./usr/local/mysql/support-files/mysql.server stop  停止mys ...

  2. C#使用ODP.NET(Oracle.ManagedDataAccess.dll)操作Oracle数据库

    在刚接触C#的时候由于公司使用的就是Oracle数据库,那么C#怎么连接Oracle数据库就成了首要去掌握的知识点了.在那时没有ODP.NET,但visual studio却对Oralce数据库的调用 ...

  3. debug版本的DLL调用release版本的DLL引发的一个问题

    stl的常用结构有 vector.list.map等. 今天碰到需要在不同dll间传递这些类型的参数,以void*作为转换参数. 比如 DLL2 的接口 add(void*pVoid); 1.在DLL ...

  4. 【Servlet】基于Jsp的微信Oauth2认证

    作者:yongh701 挂载到微信服务器上的应用程序,能够通过微信Oauth2认证,能够抓取到用户的微信信息,当然,你首先要通过微信的帐号资质审核. 一.基本思想 二.基本过程 1.登陆微信的公众平台 ...

  5. SSM框架--Spring+SpringMVC+Mybatis (IDEA)搭建

    使用idea创建一个maven项目( 这里演示 的是 web项目) 点击 Finish 然后开始配置 pom.xml文件(添加各种依赖jar包) 先去找 spring 所需的 jar包 jar包中心仓 ...

  6. MySQL中去重字段完全相同的数据

    思路:创建一个临时表,在原有的表结构基础上增加一列编号,再进行去除重复的记录 本例子是在对表 main_body_sz 进行去重 创建一个临时表 create table main_body_sz_a ...

  7. LeetCode 875. Koko Eating Bananas

    原题链接在这里:https://leetcode.com/problems/koko-eating-bananas/ 题目: Koko loves to eat bananas.  There are ...

  8. Tomcat配置二级域名的分配与访问

    回顾tomcat Tomcat是Apache软件基金会(Apache Software Foundation)的一个顶级项目,由Apache, Sun和其他一些公司及个人共同开发,是目前比较流行的We ...

  9. shell test条件检查

    Shell test 命令 Shell中的 test 命令用于检查某个条件是否成立,它可以进行数值.字符和文件三个方面的测试. 数值测试 参数 说明 -eq 等于则为真 -ne 不等于则为真 -gt ...

  10. epoch,iteration与batchsize的区别

    神经网络中epoch与iteration是不相等的 batchsize:中文翻译为批大小(批尺寸).在深度学习中,一般采用SGD训练,即每次训练在训练集中取batchsize个样本训练: iterat ...