-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy path307.cpp
More file actions
executable file
·53 lines (50 loc) · 1.39 KB
/
307.cpp
File metadata and controls
executable file
·53 lines (50 loc) · 1.39 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
class NumArray {
public:
int lowbit(int x){
return x & (-x);
}
NumArray(vector<int>& nums) {
this->length = nums.size() + 1;
this->fewick_tree = new int[this->length];
memset(this->fewick_tree,0,sizeof(int)*(length));
for (int i = 0; i < nums.size(); i++){
this->fewick_tree[i + 1] += nums[i];
int j = i + 1 + lowbit(i + 1);
if (j < this->length) fewick_tree[j] += this->fewick_tree[i + 1];
}
this->original = nums;
}
int getsum(int ed){
int res = 0;
ed += 1;
while (ed >= 1){
res += this->fewick_tree[ed];
ed -= lowbit(ed);
}
return res;
}
void update(int index, int val) {
index += 1;
int up_diff = val - original[index - 1];
original[index - 1] = val;
while (index < this->length){
fewick_tree[index] += up_diff;
index += lowbit(index);
}
}
int sumRange(int left, int right) {
if (left == 0)
return getsum(right);
return getsum(right) - getsum(left-1);
}
private:
int * fewick_tree;
int length;
vector<int> original;
};
/**
* 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);
*/