forked from Mohammed-Shoaib/Coding-Problems
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLC0307.cpp
More file actions
executable file
·63 lines (54 loc) · 1.12 KB
/
LC0307.cpp
File metadata and controls
executable file
·63 lines (54 loc) · 1.12 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
/*
Problem Statement: https://leetcode.com/problems/range-sum-query-mutable/
Space: O(n)
Author: Mohammed Shoaib, github.com/Mohammed-Shoaib
|----------------|----------|-------|
| Operations | Time | Space |
|----------------|----------|-------|
| update(i, val) | O(log n) | O(1) |
| sumRange(i, j) | O(log n) | O(1) |
|----------------|----------|-------|
*/
class FenwickTree {
private:
vector<int> ft;
public:
FenwickTree(vector<int>& nums) : ft(nums.size() + 1) {
for (int i = 0; i < nums.size(); i++)
update(i + 1, nums[i]);
}
int LSB(int x) {
return x & (-x);
}
void update(int i, int val) {
while (i < ft.size()) {
ft[i] += val;
i += LSB(i);
}
}
int rsq(int i) {
int sum = 0;
while (i != 0) {
sum += ft[i];
i -= LSB(i);
}
return sum;
}
int rsq(int i, int j) {
return rsq(j) - rsq(i - 1);
}
};
class NumArray {
private:
FenwickTree ft;
vector<int> nums;
public:
NumArray(vector<int>& nums) : ft(nums), nums(nums) {}
void update(int i, int val) {
ft.update(i + 1, val - nums[i]);
nums[i] = val;
}
int sumRange(int i, int j) {
return ft.rsq(i + 1, j + 1);
}
};