码迷,mamicode.com
首页 > 编程语言 > 详细

leetcode 307. Range Sum Query - Mutable(树状数组)

时间:2016-04-20 07:07:31      阅读:224      评论:0      收藏:0      [点我收藏+]

标签:

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.

题解:树状数组最基本的用法(点更新,区间查询)。需要注意的是这里的点更新不是把点加一个值,而是完全更新一个点的值,这就需要不仅仅更新树状数组,原数组的值也应该更新,因为可能下一个还会更新这个点,那么就需要知道它之前的值是多少。

class NumArray {
public:
    NumArray(vector<int> &nums) {
        n = nums.size();
        c=vector<int>(n+1,0);
        a=vector<int>(n+1,0);
        for(int i=1;i<=n;i++){
            update(i-1,nums[i-1]);
        }
    }
    
    int lowbit(int x){
        return x&-x;
    }
    void update(int i, int val) {
        int old = a[i+1];
        for(int k=i+1;k<=n;k+=lowbit(k)){
            c[k]-=old;
            c[k]+=val;
        }
        a[i+1]=val;
    }
    int sum(int x){
        int s=0;
        while(x>0){
            s+=c[x];
            x-=lowbit(x);
        }
        return s;
    }

    int sumRange(int i, int j) {
        return sum(j+1)-sum(i);
    }
    
private:
    int n;
    vector<int>c;
    vector<int>a;
};


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

 

leetcode 307. Range Sum Query - Mutable(树状数组)

标签:

原文地址:http://www.cnblogs.com/zywscq/p/5410994.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!