File tree Expand file tree Collapse file tree 2 files changed +12
-10
lines changed Expand file tree Collapse file tree 2 files changed +12
-10
lines changed Original file line number Diff line number Diff line change
1
+ export function lowbit ( x : number ) {
2
+ return x & - x ;
3
+ }
1
4
const add = Symbol ( ) ;
2
5
export default class NumArray {
3
6
#tree: number [ ] ;
@@ -12,12 +15,10 @@ export default class NumArray {
12
15
[ add ] ( index : number , val : number ) {
13
16
while ( index < this . #tree. length ) {
14
17
this . #tree[ index ] += val ;
15
- index += this . #lowBit ( index ) ;
18
+ index += lowbit ( index ) ;
16
19
}
17
20
}
18
- #lowBit( x : number ) {
19
- return x & - x ;
20
- }
21
+
21
22
update ( index : number , val : number ) : void {
22
23
this [ add ] ( index + 1 , val - this . #nums[ index ] ) ;
23
24
this . #nums[ index ] = val ;
@@ -30,7 +31,7 @@ export default class NumArray {
30
31
let sum = 0 ;
31
32
while ( index > 0 ) {
32
33
sum += this . #tree[ index ] ;
33
- index -= this . #lowBit ( index ) ;
34
+ index -= lowbit ( index ) ;
34
35
}
35
36
return sum ;
36
37
}
Original file line number Diff line number Diff line change 1
1
export class BinaryIndexTree < T = number > {
2
2
defaultValue : T ;
3
3
operation : ( existing : T , applied : T ) => T ;
4
- static lowbit ( x : number ) {
5
- return x & - x ;
6
- }
4
+
7
5
#tree: T [ ] ;
8
6
constructor (
9
7
public size : number ,
@@ -23,15 +21,18 @@ export class BinaryIndexTree<T = number> {
23
21
this . defaultValue = defaultValue ;
24
22
}
25
23
update ( i : number , value : T ) {
26
- for ( let p = i ; p <= this . size ; p += BinaryIndexTree . lowbit ( p ) ) {
24
+ for ( let p = i ; p <= this . size ; p += lowbit ( p ) ) {
27
25
this . #tree[ p ] = this . operation ( this . #tree[ p ] , value ) ;
28
26
}
29
27
}
30
28
query ( n : number ) {
31
29
let ans = this . defaultValue ;
32
- for ( let p = n ; p > 0 ; p -= BinaryIndexTree . lowbit ( p ) ) {
30
+ for ( let p = n ; p > 0 ; p -= lowbit ( p ) ) {
33
31
ans = this . operation ( ans , this . #tree[ p ] ) ;
34
32
}
35
33
return ans ;
36
34
}
37
35
}
36
+ export function lowbit ( x : number ) {
37
+ return x & - x ;
38
+ }
You can’t perform that action at this time.
0 commit comments