您的位置:首页 > 产品设计 > UI/UE

leecode_307 Range Sum Query - Mutable

2016-06-14 04:23 435 查看
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);


树状数组的解法参考 http://blog.csdn.net/xyt8023y/article/details/49946789
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: