File tree Expand file tree Collapse file tree 1 file changed +43
-0
lines changed Expand file tree Collapse file tree 1 file changed +43
-0
lines changed Original file line number Diff line number Diff line change 1+ const lowBit = ( x ) => x & - x
2+ class FenwickTree {
3+ constructor ( n ) {
4+ if ( n < 1 ) return
5+ this . sum = Array ( n + 1 ) . fill ( 0 )
6+ }
7+ update ( i , delta ) {
8+ if ( i < 1 ) return
9+ while ( i < this . sum . length ) {
10+ this . sum [ i ] += delta
11+ i += lowBit ( i )
12+ }
13+ }
14+ query ( i ) {
15+ if ( i < 1 ) return 0
16+ let sum = 0
17+ while ( i > 0 ) {
18+ sum += this . sum [ i ]
19+ i -= lowBit ( i )
20+ }
21+ return sum
22+ }
23+ }
24+ /**
25+ * @param {number[] } nums
26+ * @param {number } k
27+ * @return {number[] }
28+ */
29+ const getAverages = function ( nums , k ) {
30+ const n = nums . length
31+ const bit = new FenwickTree ( n )
32+ for ( let i = 0 ; i < n ; i ++ ) {
33+ bit . update ( i + 1 , nums [ i ] )
34+ }
35+ const res = Array ( n ) . fill ( - 1 )
36+ // console.log(bit)
37+ for ( let i = k ; i < n - k ; i ++ ) {
38+ const pre = bit . query ( i + 1 - k - 1 ) , cur = bit . query ( i + 1 + k )
39+ res [ i ] = ~ ~ ( ( cur - pre ) / ( k * 2 + 1 ) )
40+ }
41+
42+ return res
43+ } ;
You can’t perform that action at this time.
0 commit comments