-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathnumArray.cpp
More file actions
45 lines (41 loc) · 1018 Bytes
/
numArray.cpp
File metadata and controls
45 lines (41 loc) · 1018 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
41
42
43
44
45
class NumArray {
public:
inline int lowbit(int x) {
return x & (-x);
}
NumArray(vector<int>& nums) {
n = nums.size();
_nums = nums;
tree.resize(n + 1, 0);
for (int i = 1; i <= n; i++)
add(i, nums[i - 1]);
}
void update(int index, int val) {
int delta = val - _nums[index];
_nums[index] = val;
add(index + 1, delta);
}
void add(int x, int delta) {
for (int i = x; i <= n; i += lowbit(i)) tree[i] += delta;
}
int preSum(int i) {
int sum = 0;
while (i > 0) {
sum += tree[i];
i -= lowbit(i);
}
return sum;
}
int sumRange(int left, int right) {
return preSum(right + 1) - preSum(left);
}
private :
vector<int> tree, _nums;
int n;
};
/**
* 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);
*/