当前位置:网站首页>Leetcode sword finger offer II 041 Average value of sliding window: low space consumption solution
Leetcode sword finger offer II 041 Average value of sliding window: low space consumption solution
2022-07-19 08:39:00 【Tisfy】
【LetMeFly】 Low space consumption solution : The finger of the sword Offer II 041. Average value of sliding window
Force button topic link :https://leetcode.cn/problems/qIsx9U/
Given an integer data stream and a window size , Depending on the size of the sliding window , Calculate the average of all numbers in the sliding window .
Realization MovingAverage class :
MovingAverage(int size)Use window sizesizeInitialize object .double next(int val)Member functionsnextAn integer will be added to the sliding window every time , Please calculate and return the last... In the data streamsizeMoving average of values , That is, the average of all numbers in the sliding window .
Example :
Input : inputs = ["MovingAverage", "next", "next", "next", "next"] inputs = [[3], [1], [10], [3], [5]] Output : [null, 1.0, 5.5, 4.66667, 6.0] explain : MovingAverage movingAverage = new MovingAverage(3); movingAverage.next(1); // return 1.0 = 1 / 1 movingAverage.next(10); // return 5.5 = (1 + 10) / 2 movingAverage.next(3); // return 4.66667 = (1 + 10 + 3) / 3 movingAverage.next(5); // return 6.0 = (10 + 3 + 5) / 3
Tips :
1 <= size <= 1000-105 <= val <= 105- Call at most
nextMethod104Time
Be careful : This topic and the main station 346 The question is the same : https://leetcode-cn.com/problems/moving-average-from-data-stream/
Method 1 : simulation
This problem can be simulated .
- use
int sizeRecord “ The sliding window ” Maximum size of - use
int sumRecord “ The sliding window ” Sum of all values in - use
int numRecord “ The sliding window ” Number of digits of
So what is used to simulate windows ? In fact, using queues is a great choice .
But you can also see from this title , This solution mainly uses low space consumption to solve the problem , So I decided to use Static array To simulate a queue .
Because the length of the queue is fixed , So when we open up arrays , The size of the development is “ The sliding window ” The size is ok .
- use
int* aSimulation queue - use
int locRecord the subscript of the element about to leave the team
private:
int size;
int sum;
int num;
int *a; // Array
int loc; // Which should be removed
public:
/** Initialize your data structure here. */
MovingAverage(int size): size(size), sum(0), num(0), a(new int[size]), loc(0) {
}
Direction “ The sliding window ” When adding new elements in , First, check whether the queue is full .
- If dissatisfied, add new elements
- If it is full, delete the old element and add a new element
if (num < size) {
// At first , The window hasn't been filled yet
sum += val;
a[num++] = val;
return ONE * sum / num; // among ONE yes double Type of 1
}
else {
sum -= a[loc];
sum += val;
a[loc++] = val;
loc %= size;
return ONE * sum / num;
}
Running results :

If you want to be more rigorous , It can be used during class destructions deletenew Out of the array
~MovingAverage() {
delete[] a;
}
The running time has been reduced

- Time complexity O ( n ) O(n) O(n), among n n n Is the number of elements to add
- Spatial complexity O ( m ) O(m) O(m), among m m m yes “ The sliding window ” Size
AC Code
C++
const double ONE = 1;
class MovingAverage {
private:
int size;
int sum;
int num;
int *a; // Array
int loc; // Which should be removed
public:
/** Initialize your data structure here. */
MovingAverage(int size): size(size), sum(0), num(0), a(new int[size]), loc(0) {
}
~MovingAverage() {
delete[] a;
}
double next(int val) {
if (num < size) {
// At first , The window hasn't been filled yet
sum += val;
a[num++] = val;
return ONE * sum / num;
}
else {
sum -= a[loc];
sum += val;
a[loc++] = val;
loc %= size;
return ONE * sum / num;
}
}
};
Synchronous posting on CSDN, Originality is not easy. , Reprint please attach Link to the original text Oh ~
Tisfy:https://letmefly.blog.csdn.net/article/details/125819216
边栏推荐
- Graphite thickness measurement
- 把HBuilderX的主题变成vscode
- JS学习笔记09-12:原型对象以及Foreach+tostring及回收站
- SPARK闲杂--为什么复用Exchange和subquery
- matlab导入小数点后9位以上的浮点数
- WVPPRO-ZLM-GB21818-摄像头
- Softmax 回归 + 损失函数 + 图片分类数据集
- Redis的发布和订阅
- Introduction to deep learning exercises sorting in the first week of deep learning
- Redis6 new data type - hyperloglog
猜你喜欢
随机推荐
Hand in hand practice a DAPP, the road to Web3.0!
#yyds干货盘点#Cross-origin 跨域请求
Junit5
Introduction to flutter flutter calculates the last 1 month, 3 months, half a year, 12 months
搭建嵌入式开发环境
JS学习笔记04-05——构造函数的修改以及使用工厂方法创建
Error received from peer ipv4/connection reset by peer paddleserving
Opportunities and challenges of Brazilian mobile game Investment Agency
Picture browser
Softmax regression + loss function + image classification dataset
Matlab imports floating-point numbers with more than 9 digits after the decimal point
Gateway新一代网关
Microservices and microservice architecture
5g at that time, where will driverless driving go in the future?
5.1 安全漏洞與防範
力扣382链表随机节点笔记
Convex mirror 3D glass contour scanning
ES6学习-函数(严格模式,高阶函数,闭包)
使用arduino开发esp8266和esp32时首选项设置方法
JS learning notes 09-12: prototype objects, foreach+tostring and recycle bin









