-
Notifications
You must be signed in to change notification settings - Fork 0
/
NumArray.java
78 lines (70 loc) · 1.88 KB
/
NumArray.java
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
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
import jdk.javadoc.internal.doclets.formats.html.SourceToHTMLConverter;
class NumArray {
int[] tree;
int n;
public NumArray(int[] nums) {
if (nums.length > 0) {
n = nums.length;
tree = new int[n * 2];
buildTree(nums);
}
}
private void buildTree(int[] nums) {
for (int i = n, j = 0; i < 2 * n; i++, j++)
tree[i] = nums[j];
for (int i = n - 1; i > 0; --i)
tree[i] = tree[i * 2] + tree[i * 2 + 1];
}
public void update(int pos, int val) {
pos += n;
tree[pos] = val;
while (pos > 0) {
int left = pos;
int right = pos;
if (pos % 2 == 0) {
right = pos + 1;
} else {
left = pos - 1;
}
// parent is updated after child is updated
tree[pos / 2] = tree[left] + tree[right];
pos /= 2;
}
}
public int sumRange(int l, int r) {
// get leaf with value 'l'
l += n;
// get leaf with value 'r'
r += n;
int sum = 0;
while (l <= r) {
if ((l % 2) == 1) {
sum += tree[l];
l++;
}
if ((r % 2) == 0) {
sum += tree[r];
r--;
}
l /= 2;
r /= 2;
}
return sum;
}
public static void main(String[] args) {
int[] nums = {1, 3, 5};
NumArray na = new NumArray(nums);
na.printArray();
na.sumRange(0, 2);
}
public void printArray() {
for (int i = 0; i < tree.length; i++) {
System.out.println(tree[i]);
}
}
}
/**
* Your NumArray object will be instantiated and called as such: NumArray obj =
* new NumArray(nums); obj.update(index,val); int param_2 =
* obj.sumRange(left,right);
*/