首页 > 其他 > 详细

LeetCode 307. Range Sum Query - Mutable

时间:2020-06-03 16:25:38      阅读:33      评论:0      收藏:0      [点我收藏+]

题目

动态就区间和,线段树,树状数组都可以

class NumArray {
public:
    int n;
    int c[100005];
    vector<int> nums;
    NumArray(vector<int>& nums) {
        this->nums = nums;
        memset(c,0,sizeof(c));
        n = nums.size();
        for (int i = 0; i < nums.size(); i++)
        {
            add(i+1,nums[i]);
        }
       
    }

    void update(int i, int val) {
        
        add(i + 1, val - this->nums[i]);
        this->nums[i]=val;
    }

    int sumRange(int i, int j) {

        return sum(j + 1) - sum(i);
    }

    int lowbit(int x)
    {
        return x & (-x);
    }

    void add(int pos, int value)
    {
        while (pos <= n)
        {
            c[pos] += value;
            pos += lowbit(pos);
        }
    }

    int sum(int pos)
    {
        int sum = 0;
        while (pos)
        {
            sum += c[pos];
            pos -= lowbit(pos);
        }

        return sum;
    }
};

/**
 * 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 307. Range Sum Query - Mutable

原文:https://www.cnblogs.com/dacc123/p/13037847.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!