给定一个整数数组 nums,求出数组从索引 i 到 j (i ≤ j) 范围内元素的总和,包含 i, j 两点。
update(i, val) 函数可以通过将下标为 i 的数值更新为 val,从而对数列进行修改。
示例:
Given nums = [1, 3, 5]
sumRange(0, 2) -> 9
update(1, 2)
sumRange(0, 2) -> 8
说明:
- 数组仅可以在 update 函数下进行修改。
- 你可以假设 update 函数与 sumRange 函数的调用次数是均匀分布的。
使用线段树的方法解决,实际复杂读是O(logN)
class NumArray {
private:
vector<int> arr;
vector<int> tree;
public:
void build_tree(int node, int start, int end) {
if (start == end) {
tree[node] = arr[start];
return;
}
int mid = start + (end - start) / 2;
int left_node = node * 2 + 1;
int right_node = node * 2 + 2;
build_tree(left_node, start, mid);
build_tree(right_node, mid + 1, end);
tree[node] = tree[left_node] + tree[right_node];
}
void update_tree(int node, int start, int end, int idx, int val) {
if (start == end) {
arr[idx] = val;
tree[node] = val;
return;
}
int mid = start + (end - start) / 2;
int left_node = node * 2 + 1;
int right_node = node * 2 + 2;
if (idx >= start && idx <= mid)
update_tree(left_node, start, mid, idx, val);
else
update_tree(right_node, mid + 1, end, idx, val);
tree[node] = tree[left_node] + tree[right_node];
}
int query_tree(int node, int start, int end, int L, int R) {
if (R<start || L > end)
return 0;
else if (L <= start && end <= R)
return tree[node];
else if (start == end)
return tree[node];
int mid = start + (end - start) / 2;
int left_node = node * 2 + 1;
int right_node = node * 2 + 2;
int sum_left = query_tree(left_node, start, mid, L, R);
int sum_right = query_tree(right_node, mid+1, end, L, R);
return sum_left + sum_right;
}
NumArray(vector<int> nums) {
if(nums.size()==0)
return;
arr.assign(nums.begin(), nums.end());
tree.resize(nums.size()*4);
build_tree(0,0,nums.size()-1);
}
void update(int i, int val) {
update_tree(0, 0, arr.size()-1, i, val);
}
int sumRange(int i, int j) {
return query_tree(0,0,arr.size()-1,i,j);
}
};
/**
* Your NumArray object will be instantiated and called as such:
* NumArray obj = new NumArray(nums);
* obj.update(i,val);
* int param_2 = obj.sumRange(i,j);
*/