【刷题】Leetcode307(树状数组)

树状数组详解见https://blog.csdn.net/moX980/article/details/107658403

Leetcode307

image-20200808212432660

题目分析:典型的树状数组

ps:

  1. 树状数组下标从1开始 lowbit(0) = 0 没有意义 而题目给出的数组是从0开始,所以要做转换
  2. update时直接更新的是数值 不是变化量 所以要记录原始数组便于求变化量
#define lowbit(x) ((x) & (-x))
class NumArray {
private:
    vector<int> c;
    vector<int> origin;
    int s(int ind){
        ind++;
        int sum = 0;
        while(ind) sum += this->c[ind], ind -= lowbit(ind);
        return sum;
    }
    void add(int i, int val, int n){
        while(i <= n) this->c[i] += val, i += lowbit(i);
        return ;
    }
public:
    NumArray(vector<int>& nums) {
        this->origin.push_back(0);
        this->origin.insert(this->origin.end(), nums.begin(), nums.end());
        this->c.insert(this->c.end(), nums.size() + 1, 0);
        for(int i = 1; i < this->origin.size(); i++){
            add(i, this->origin[i], this->c.size() - 1);
        }
           
    }
    
    void update(int i, int val) {
        i++;
        add(i, val - this->origin[i], this->c.size() - 1);
        this->origin[i] = val;
        return ;
    }
    
    int sumRange(int i, int j) {
        i--;
        return (this->s(j) - this->s(i));
    }
};

/**
 * 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);
 */
©️2020 CSDN 皮肤主题: 黑客帝国 设计师:上身试试 返回首页