-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path307.range-sum-query-mutable.cpp
More file actions
65 lines (56 loc) · 1.31 KB
/
Copy path307.range-sum-query-mutable.cpp
File metadata and controls
65 lines (56 loc) · 1.31 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
64
/*
* @lc app=leetcode id=307 lang=cpp
*
* [307] Range Sum Query - Mutable
*/
// @lc code=start
#include "bits/stdc++.h"
using namespace std;
class NumArray {
public:
vector<int> bit;
vector<int> data;
int lowBit(int x){
return x & (-x);
}
int sum(int idx){
int res = 0;
while (idx > 0)
{
/* code */
res += bit[idx];
idx -= lowBit(idx);
}
return res;
}
NumArray(vector<int>& nums) {
bit = vector<int>(nums.size() + 1, 0);
data = nums;
for(int i = 1; i < nums.size() + 1; ++i){
bit[i] += nums[i - 1];
int j = i + lowBit(i);
if(j <= nums.size()) bit[j] += bit[i];
}
}
void update(int index, int val) {
int diff = val - data[index];
data[index] = val;
++index;
while (index <= data.size())
{
/* code */
bit[index] += diff;
index += lowBit(index);
}
}
int sumRange(int left, int right) {
return sum(right + 1) - sum(left);
}
};
/**
* 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);
*/
// @lc code=end