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.
树状数组详解这位同学写的相当不错。。主要是有几个函数1.lowbit:树状数组用来做2分的。。很奇妙的x&-x方法。 2.add(pos,value)在pos位置加value 3.sum方法算0--pos位置的部分和。下面是树状数组的模板:
int lowbit(int pos){
return pos&(-pos);
}
void add(int pos, int value){
while(pos < c.size()){
c[pos] += value;
pos += lowbit(pos);
}
}
int sum(int pos){
int res = 0;
while(pos > 0){
res += c[pos];
pos -= lowbit(pos);
}
return res;
}
而leetcode的这道题,显然是就在树状数组上改了改。。需要的代码如下
void update(int i, int val) {
int b = a[i];
int d= val - b;
a[i] = val;
add(i+1,d);
}
int sumRange(int i, int j) {
return sum(j+1) - sum(i);//前面树状数组模板里的pos是数组下标加一的
}