Skip to content

Commit e2d02a2

Browse files
authored
Create BinaryIndexedTree.java
1 parent 44d5f46 commit e2d02a2

File tree

1 file changed

+28
-0
lines changed

1 file changed

+28
-0
lines changed

BinaryIndexedTree.java

+28
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
class BinaryIndexedTree {
2+
int[] tree;
3+
4+
static int lowbit(int x) {
5+
return x & -x;
6+
}
7+
public BinaryIndexedTree(int[] nums) {
8+
tree = new int[nums.length+1];
9+
for (int i = 0; i < nums.length; i++)
10+
add(i, nums[i]);
11+
}
12+
public int query(int x) { // sum(nums[:x])
13+
int ans = 0;
14+
for (int i = x; i > 0; i -= lowbit(i))
15+
ans += tree[i];
16+
return ans;
17+
}
18+
public void add(int x, int u) { // nums[x] += u
19+
for (int i = x+1; i < tree.length; i += lowbit(i))
20+
tree[i] += u;
21+
}
22+
public void set(int x, int y) { // nums[x] = y
23+
add(x, y - query(x+1) + query(x));
24+
}
25+
public int sumRange(int l, int r) {
26+
return query(r+1) - query(l);
27+
}
28+
}

0 commit comments

Comments
 (0)