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.
题目还要求使用update函数更新arr中位置i的值为val,这就要利用add函数来实现,注意add函数是在位置pos上追加一个值value,而不是覆盖,因此我们需要计算值的变化量,把它追加到相应位置,并且一定要记得更新arr,否则下次得到的变化量是错误的。
class NumArray {
private:
vector<int> c;
vector<int> m_nums;
public:
NumArray(vector<int> &nums)
{
c.resize(nums.size()+1);
m_nums = nums;
for(int i = 0; i < nums.size(); i++){
add(i+1,nums[i]);
}
}
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;
}
void update(int i, int val) {
int ori = m_nums[i];
int delta = val - ori;
m_nums[i] = val;
add(i+1,delta);
}
int sumRange(int i, int j) {
return sum(j+1)-sum(i);
}
};
// Your NumArray object will be instantiated and called as such:
// NumArray numArray(nums);
// numArray.sumRange(0, 1);
// numArray.update(1, 10);
// numArray.sumRange(1, 2);