1
var NumArray = function (nums) {
2
this.nums = nums;
3
this.n = nums.length;
4
this.fenwickTree = new Array(this.n + 1).fill(0);
5
nums.forEach((num, index) => this.init(index, num));
6
};
7

8
NumArray.prototype.init = function (index, val) {
9
let j = index + 1;
10
while (j <= this.n) {
11
this.fenwickTree[j] += val;
12
j += this.lsb(j);
13
}
14
};
15

16
NumArray.prototype.lsb = function (index) {
17
return index & ~(index - 1);
18
};
19

20
NumArray.prototype.update = function (index, val) {
21
const diff = val - this.nums[index];
22
this.nums[index] = val;
23
this.init(index, diff);
24
};
25

26
NumArray.prototype.getSum = function (index) {
27
let j = index + 1;
28
let sum = 0;
29

30
while (j > 0) {
31
sum += this.fenwickTree[j];
32
j -= this.lsb(j);
33
}
34

35
return sum;
36
};
37

38
NumArray.prototype.sumRange = function (left, right) {
39
return this.getSum(right) - this.getSum(left - 1);
40
};

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0