-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathRangeSumQueryMutable.java
More file actions
63 lines (53 loc) · 1.9 KB
/
Copy pathRangeSumQueryMutable.java
File metadata and controls
63 lines (53 loc) · 1.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
// Given an integer array nums, find the sum of the elements between indices i and j (i ≤ j), inclusive.
// The update(i, val) function modifies nums by updating the element at index i to val.
// See: https://leetcode.com/problems/range-sum-query-mutable/
package leetcode.design;
public class RangeSumQueryMutable {
// TODO: Add Segment Tree solution
// TODO: Add Sqrt Decomposition solution
// See: https://www.youtube.com/watch?v=CWDQJGaN1gY
// See: https://www.geeksforgeeks.org/binary-indexed-tree-or-fenwick-tree-2/
class NumArray {
// Array representation of a Binary Indexed Tree
private int[] biTree;
private int[] nums;
public NumArray(int[] nums) {
this.nums = nums;
biTree = new int[nums.length + 1];
for (int i = 0; i < nums.length; i++) {
updateHelper(i, nums[i]);
}
}
public void updateHelper(int i, int val) {
i = i + 1;
while (i <= nums.length) {
biTree[i] += val;
i += i & (-i);
}
}
public void update(int i, int val) {
int diff = val - nums[i];
nums[i] = val;
updateHelper(i, diff);
}
private int getSum(int i) {
int sum = 0;
++i;
while (i > 0) {
sum += biTree[i];
i -= i & (-i);
}
return sum;
}
public int sumRange(int i, int j) {
return getSum(j) - getSum(i - 1);
}
}
public static void main(String[] args) {
NumArray na = new RangeSumQueryMutable().new NumArray(new int[] {1, 3, 5});
System.out.println(na.sumRange(0, 2));
// System.out.println(na.sumRange(0, 1));
na.update(1, 2);
System.out.println(na.sumRange(0, 2));
}
}