Skip to content

Commit 093323a

Browse files
authored
Update 307-range-sum-query-mutable.js
1 parent 120dc0a commit 093323a

File tree

1 file changed

+65
-0
lines changed

1 file changed

+65
-0
lines changed

307-range-sum-query-mutable.js

Lines changed: 65 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,68 @@
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+
/**
26+
* @param {number[]} nums
27+
*/
28+
var NumArray = function(nums) {
29+
this.nums = nums
30+
const n = nums.length
31+
this.bit = new FenwickTree(n)
32+
for(let i = 1; i <= n; i++) {
33+
this.bit.update(i, nums[i - 1])
34+
}
35+
};
36+
37+
/**
38+
* @param {number} index
39+
* @param {number} val
40+
* @return {void}
41+
*/
42+
NumArray.prototype.update = function(index, val) {
43+
const delta = val - this.nums[index]
44+
this.nums[index] = val
45+
this.bit.update(index + 1, delta)
46+
};
47+
48+
/**
49+
* @param {number} left
50+
* @param {number} right
51+
* @return {number}
52+
*/
53+
NumArray.prototype.sumRange = function(left, right) {
54+
return this.bit.query(right + 1) - this.bit.query(left)
55+
};
56+
57+
/**
58+
* Your NumArray object will be instantiated and called as such:
59+
* var obj = new NumArray(nums)
60+
* obj.update(index,val)
61+
* var param_2 = obj.sumRange(left,right)
62+
*/
63+
64+
// another
65+
166
/**
267
* @param {number[]} nums
368
*/

0 commit comments

Comments
 (0)