树状数组,处理更快,更大范围的前缀和
class TA {
public:
int n;
vector<int>c;//关键区间数组
TA(int _n) {
n=_n;
c.resize(_n+1);
}
int lb(int i){
return i&-i;
}
void update(int index, int d) {//更新,先计算差值,对每个包含i的c[j]进行增加,所有包含i的c[j]为j=i,i+lb(i),....
for(int i=index+1;i<c.size();i+=lb(i))c[i]+=d;
}
int presum(int i){
int s=0;
for(;i>0;i=i-lb(i))s+=c[i];
return s;
}
int sumRange(int left, int right) { //这里的left和right都是原来数组中的下标包括0
return presum(right+1)-presum(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);
*/