动态就区间和,线段树,树状数组都可以
class NumArray {
public:
int n;
int c[100005];
vector<int> nums;
NumArray(vector<int>& nums) {
this->nums = nums;
memset(c,0,sizeof(c));
n = nums.size();
for (int i = 0; i < nums.size(); i++)
{
add(i+1,nums[i]);
}
}
void update(int i, int val) {
add(i + 1, val - this->nums[i]);
this->nums[i]=val;
}
int sumRange(int i, int j) {
return sum(j + 1) - sum(i);
}
int lowbit(int x)
{
return x & (-x);
}
void add(int pos, int value)
{
while (pos <= n)
{
c[pos] += value;
pos += lowbit(pos);
}
}
int sum(int pos)
{
int sum = 0;
while (pos)
{
sum += c[pos];
pos -= lowbit(pos);
}
return sum;
}
};
/**
* 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);
*/