File tree Expand file tree Collapse file tree 2 files changed +37
-0
lines changed Expand file tree Collapse file tree 2 files changed +37
-0
lines changed Original file line number Diff line number Diff line change 334
334
343|[ Integer Break] ( ./solutions/0343-integer-break.js ) |Medium|
335
335
344|[ Reverse String] ( ./solutions/0344-reverse-string.js ) |Easy|
336
336
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|
337
338
347|[ Top K Frequent Elements] ( ./solutions/0347-top-k-frequent-elements.js ) |Medium|
338
339
349|[ Intersection of Two Arrays] ( ./solutions/0349-intersection-of-two-arrays.js ) |Easy|
339
340
350|[ Intersection of Two Arrays II] ( ./solutions/0350-intersection-of-two-arrays-ii.js ) |Easy|
Original file line number Diff line number Diff line change
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
+ } ;
You can’t perform that action at this time.
0 commit comments