给定一个整数数组 nums
, 然后你需要实现两个函数:
update(i, val)
将数组下标为i的元素修改为valsumRange(l, r)
返回数组下标在[l, r][l,r]区间的元素的和
样例
样例 1:
输入:
nums = [1, 3, 5]
sumRange(0, 2)
update(1, 2)
sumRange(0, 2)
输出:
9
8
样例 2:
输入:
nums = [0, 9, 5, 7, 3]
sumRange(4, 4)
sumRange(2, 4)
update(4, 5)
update(1, 7)
update(0, 8)
sumRange(1, 2)
输出:
3
15
12
注意事项
- 数组只能通过update函数进行修改。
- 你可以假设 update 函数与 sumRange 函数的调用数量是均匀的。
class NumArray {
public:
vector<int> ret;
NumArray(vector<int> nums) {
ret = nums;
}
void update(int i, int val) {
ret[i] = val;
}
int sumRange(int i, int j) {
int sum = 0;
for(int left = i; left <= j; left++)
{
sum += ret[left];
}
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);
*/