Leetcode195: Range Sum Query - Mutable

243 篇文章 0 订阅

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

The update(i, val) function modifies nums by updating the element at index i to val.

Example:

Given nums = [1, 3, 5]

sumRange(0, 2) -> 9
update(1, 2)
sumRange(0, 2) -> 8

Note:

  1. The array is only modifiable by the update function.
  2. You may assume the number of calls to update and sumRange function is distributed evenly.
题目要求快速的处理数组的部分和,因此很容易联想到树状数组,树状数组是一种用于通过辅助数组和位置算法实现动态管理部分和的一种算法,其核心函数为lowbit、add、sum,当我们需要加入一个元素时,使用add函数向某个位置注入值,当需要求0~某位置的和时,调用sum函数传入这个位置即可,树状数组的代码简洁但是难以理解,所以建议采用背诵的方式

题目还要求使用update函数更新arr中位置i的值为val,这就要利用add函数来实现,注意add函数是在位置pos上追加一个值value,而不是覆盖,因此我们需要计算值的变化量,把它追加到相应位置,并且一定要记得更新arr,否则下次得到的变化量是错误的。

class NumArray {
private:
    vector<int> c;
    vector<int> m_nums;
    
public:
    NumArray(vector<int> &nums) 
    {
        c.resize(nums.size()+1);
        m_nums = nums;
        for(int i = 0; i < nums.size(); i++){
            add(i+1,nums[i]);
        }
    }
    int lowbit(int pos)
    {
        return pos&(-pos);
    }
    void add(int pos, int value)
    {
        while(pos < c.size()){
            c[pos] += value;
            pos += lowbit(pos);
        }
    }
    int sum(int pos){
        int res = 0;
        while(pos > 0){
            res += c[pos];
            pos -= lowbit(pos);
        }
        return res;
    }
    void update(int i, int val) {
        int ori = m_nums[i];
        int delta = val - ori;
        m_nums[i] = val;
        add(i+1,delta);
    }

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


// Your NumArray object will be instantiated and called as such:
// NumArray numArray(nums);
// numArray.sumRange(0, 1);
// numArray.update(1, 10);
// numArray.sumRange(1, 2);


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值