307. Range Sum Query - Mutable
Given an integer array nums, find the sum of the elements between indices i and j (i ≤ j), inclusive.
The update(i, val) function modifies nums by updating the element at index i to val.
Example:
Given nums = [1, 3, 5]
sumRange(0, 2) -> 9
update(1, 2)
sumRange(0, 2) -> 8
Note:
The array is only modifiable by the update function.
You may assume the number of calls to update and sumRange function is distributed evenly.
// Binary Index Tree
class NumArray {
public:
NumArray(vector<int> nums) : BIT(nums.size() + 1, 0) {
for (int i = 0; i < nums.size(); ++i) {
int val = nums[i];
int index = i + 1;
while (index < BIT.size()) {
BIT[index] += val;
index += (index & -index);
}
}
}
int getSum(int i) {
int sum = 0;
int index = i + 1;
while (index > 0) {
sum += BIT[index];
index -= (index & -index);
}
return sum;
}
void update(int i, int val) { // time: O(logn)
int orig = getSum(i) - getSum(i - 1);
int diff = val - orig;
int index = i + 1;
while (index < BIT.size()) {
BIT[index] += diff;
index += (index & -index);
}
}
int sumRange(int i, int j) { // time: O(logn)
return getSum(j) - getSum(i - 1);
}
vector<int> BIT;
};
Last updated
Was this helpful?