LandscapeMi

landscapemi的博客

leetcode: Segment Tree:Range Sum Query - Mutable(307)

https://leetcode.com/problems/range-sum-query-mutable/


class NumArray {
public:
    NumArray(vector<int> &nums) {
        num.resize(nums.size() + 1);
        bit.resize(nums.size() + 1);
        for (int i = 0; i < nums.size(); ++i) {
            update(i, nums[i]);
        }
    }
    void update(int i, int val) {
        int diff = val - num[i + 1];
        for (int j = i + 1; j < num.size(); j += (j&-j)) {
            bit[j] += diff;
        }
        num[i + 1] = val;
    }
    int sumRange(int i, int j) {
        return getSum(j + 1) - getSum(i);
    }    
    int getSum(int i) {
        int res = 0;
        for (int j = i; j > 0; j -= (j&-j)) {
            res += bit[j];
        }
        return res;
    }

private:
    vector<int> num;
    vector<int> bit;
};
阅读更多
版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/mijian1207mijian/article/details/52385188
个人分类: leetcode(c++)
上一篇leetcode:Data Stream as Disjoint Intervals(352)
下一篇leetcode:Trie:Implement Trie (Prefix Tree)(208)
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

关闭
关闭