Range Sum Query - Mutable

本文介绍了一种使用线段树实现数组元素实时更新及区间求和的方法。通过构建特殊的线段树结构,可以高效地完成区间求和操作,并支持对数组任意位置的值进行更新。具体实现中,利用了数组来存储线段树节点,简化了数据结构的维护。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Problem


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


Solution

自己创建一个segment tree的数据结构老是超时。。

参考了官方的答案,用数组来实现一个数,挺巧妙的。

class NumArray {
    int N;
    vector<int> tree;
    int find( int left, int right) {
        if(left > right) return 0;
        if(left == right) return tree[left];
        int sum = 0;
        if( left%2 == 1 ){
            sum += tree[left++];
        } 
        if(right%2 == 0 ) {
            sum += tree[right--];
        }
        return sum += find( left/2, right/2);
    }
public:
    NumArray(vector<int> &nums): N(nums.size()) {
        
        tree.resize(2*N,0);
        for( int i = N; i < 2*N; i++){
            tree[i] = nums[i-N];
        }
        for( int i = N - 1; i > 0; i--){
            tree[i] = tree[2*i] + tree[2*i+1];
        }
    }

    void update(int idx, int val) {
        idx += N;
        int diff = val - tree[idx];
        while(idx != 0) {
            tree[idx] += diff;
            idx /= 2;
        }
    }

    int sumRange(int i, int j) {
        return find( i + N, j + N);
    }
};


// 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);






评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值