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:
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 O(n), sumrange O(1);
class NumArray {
public:
vector<int> sum;
vector<int> num_vec;
NumArray(vector<int> &nums) {
num_vec=nums;
sum.push_back(0);
for (int i=0;i<nums.size();i++)
sum.push_back(sum[i]+nums[i]);
}
void update(int i, int val) {
for (int j=i+1;j<sum.size();j++)
sum[j]=sum[j]+val-num_vec[i];
num_vec[i]=val;
}
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);