07. Range Sum Query - Mutable

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:

  1. The array is only modifiable by the update function.
  2. You may assume the number of calls to update and sumRange function is distributed evenly.

解题思路:区间查询,单点更新。线段树(segment tree)或者树状数组(binary index tree)的典型应用。

树状数组:

#define lowbit(i) ((i)&(-i))
class NumArray {
public:
    NumArray(vector<int> nums) {
        _nums=nums;
        C.resize(nums.size()+1);
        for(int i=0;i<nums.size();i++)
           init(i,nums[i]);
    }
    void init(int i,int val){
        for(int x=i+1;x<C.size();x+=lowbit(x)){
            C[x]+=val;
        }
    }
    void update(int i, int val) {
        int diff=val-_nums[i];
        _nums[i]=val;
        init(i,diff);
    }
    
    int sumRange(int i, int j) {
        int sum=0;
        for(int x=j+1;x>0;x-=lowbit(x))
            sum+=C[x];
        for(int x=i;x>0;x-=lowbit(x))
            sum-=C[x];
        return sum;
    }
private:
    vector<int>C;
    vector<int>_nums;
};

/**
 * 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);
 */

 

posted @ 2017-04-10 16:28  Tsunami_lj  阅读(105)  评论(0编辑  收藏  举报