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

原创 2016年08月31日 14:58:12

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;
};
版权声明:本文为博主原创文章,未经博主允许不得转载。

※ Leetcode - Segment Tree - 307. Range Sum Query - Mutable (线段树+树状数组两种解法以及模板的常见问题解析)

1. Problem Description Given an integer array nums, find the sum of the elements between indices i a...

(LeetCode 307) Range Sum Query - Mutable(Segment Tree)

Q: Given an integer array nums, find the sum of the elements between indices i and j (i ≤ j), inclu...

LeetCode(307) Range Sum Query - Mutable

题目Given an integer array nums, find the sum of the elements between indices i and j (i ≤ j), inclusi...
  • fly_yr
  • fly_yr
  • 2015年12月12日 17:21
  • 3106

[LeetCode 307] Range Sum Query - Mutable

Given an integer array nums, find the sum of the elements between indices i and j (i ≤ j), inclusive...
  • sbitswc
  • sbitswc
  • 2015年12月04日 14:57
  • 2773

(LeetCode 307) Range Sum Query - Mutable(树状数组讲解)

Q: Given an integer array nums, find the sum of the elements between indices i and j (i ≤ j), incl...

LeetCode 307. Range Sum Query - Mutable(区间之和)

原题网址:https://leetcode.com/problems/range-sum-query-mutable/ Given an integer array nums, find t...
  • jmspan
  • jmspan
  • 2016年04月20日 07:58
  • 367

Leetcode (307) Range Sum Query - Mutable

Given an integer array nums, find the sum of the elements between indices i and j (i ≤ j), inclusive...

Leetcode 307. Range Sum Query - Mutable (Python)

题目大意构建一个数据结构,共有两种操作方式 sumRange(i,j):计算[i,j]范围内数组和 update(i,val):将位于数组坐标i的元素值改为val 算法使用线段树即可代码class S...

LeetCode 307 Range Sum Query - Mutable(树状数组 || 线段树)

Given an integer array nums, find the sum of the elements between indices i and j (i ≤ j), inclusive...

Leetcode 307: Range Sum Query - Mutable 之BIT

题目传送门: Leetcode 307.Range Sum Query - Mutable题目 Given an integer array nums, find the sum of the ...
内容举报
返回顶部
收藏助手
不良信息举报
您举报文章:leetcode: Segment Tree:Range Sum Query - Mutable(307)
举报原因:
原因补充:

(最多只允许输入30个字)