Skip to content

Commit 754988a

Browse files
committed
Add solution #346
1 parent d1a09b6 commit 754988a

File tree

2 files changed

+37
-0
lines changed

2 files changed

+37
-0
lines changed

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -334,6 +334,7 @@
334334
343|[Integer Break](./solutions/0343-integer-break.js)|Medium|
335335
344|[Reverse String](./solutions/0344-reverse-string.js)|Easy|
336336
345|[Reverse Vowels of a String](./solutions/0345-reverse-vowels-of-a-string.js)|Easy|
337+
346|[Moving Average from Data Stream](./solutions/0346-moving-average-from-data-stream.js)|Easy|
337338
347|[Top K Frequent Elements](./solutions/0347-top-k-frequent-elements.js)|Medium|
338339
349|[Intersection of Two Arrays](./solutions/0349-intersection-of-two-arrays.js)|Easy|
339340
350|[Intersection of Two Arrays II](./solutions/0350-intersection-of-two-arrays-ii.js)|Easy|
Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
/**
2+
* 346. Moving Average from Data Stream
3+
* https://leetcode.com/problems/moving-average-from-data-stream/
4+
* Difficulty: Easy
5+
*
6+
* Given a stream of integers and a window size, calculate the moving average of all integers
7+
* in the sliding window.
8+
*
9+
* Implement the MovingAverage class:
10+
* - MovingAverage(int size) Initializes the object with the size of the window size.
11+
* - double next(int val) Returns the moving average of the last size values of the stream.
12+
*/
13+
14+
/**
15+
* @param {number} size
16+
*/
17+
var MovingAverage = function(size) {
18+
this.window = [];
19+
this.maxSize = size;
20+
this.sum = 0;
21+
};
22+
23+
/**
24+
* @param {number} val
25+
* @return {number}
26+
*/
27+
MovingAverage.prototype.next = function(val) {
28+
this.window.push(val);
29+
this.sum += val;
30+
31+
if (this.window.length > this.maxSize) {
32+
this.sum -= this.window.shift();
33+
}
34+
35+
return this.sum / this.window.length;
36+
};

0 commit comments

Comments
 (0)