-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy path307.cpp
More file actions
40 lines (38 loc) · 943 Bytes
/
Copy path307.cpp
File metadata and controls
40 lines (38 loc) · 943 Bytes
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
class NumArray {
vector<int> array;
public:
NumArray(vector<int> nums) {
int n = nums.size();
array = vector<int>(2 * n, 0);
for (int i = n, j = 0; i < 2 * n; ++i, ++j)
array[i] = nums[j];
for (int i = n - 1; i > 0; --i)
array[i] = array[i * 2] + array[i * 2 + 1];
}
void update(int i, int val) {
i += array.size() / 2;
int prev = array[i];
while (i > 0) {
array[i] += val - prev;
i /= 2;
}
}
int sumRange(int i, int j) {
int sum = 0;
i += array.size() / 2;
j += array.size() / 2;
while (i <= j) {
if (i % 2 == 1) {
sum += array[i];
++i;
}
if (j % 2 == 0) {
sum += array[j];
--j;
}
i /= 2;
j /= 2;
}
return sum;
}
};