树状数组-线段树模板题(leetcode-307)

考察点:树状数组,线段树;
树状数组就是声明一个新的数组来表述树状数组,然后根据树的二进制特征进行update和getSum。线段树是根据数组生成一棵树。
下面是经典的树状数组代码:

class NumArray {
public:
    vector<int> tree;
    vector<int> Nums;
    int len;
    NumArray(vector<int> nums) {
        len = nums.size();
        Nums = nums;
        tree = vector<int>(len+1, 0);
        for (int i=0; ivoid init(int i, int val) {
        i++;
        while (i <= len) {
            tree[i] += val;
            i += (i & -i);
        }
    }

    void update(int i, int val) {
        int temp = val - Nums[i];
        Nums[i] = val;
        init(i, temp);
    }

    int getSum(int i) {
        int sum = 0;
        i++;
        while (i > 0) {
            sum += tree[i];
            i -= (i & -i);
        }
        return sum;
    }

    int sumRange(int i, int j) {
        return getSum(j) - getSum(i-1);
    }
};

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

你可能感兴趣的:(算法,leetcode,tree)