Binary Indexed Tree-307. Range Sum Query - Mutable

区间求和与更新算法
本文介绍了一种高效实现数组区间求和及元素更新的方法。通过预处理数组的累积和,实现了快速查询任意两个索引之间的元素总和,并在元素更新时调整累积和。这种方法适用于数组元素频繁修改且需要快速查询区间和的场景。

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.

 



 
 
 
class NumArray
 2 {
 3 public:
 4     NumArray(vector<int> &nums) 
 5     {
 6         sums.push_back(0);
 7         for (int i = 0; i < nums.size(); i++)
 8         {
 9             sums.push_back(sums[i] + nums[i]);
10             values.push_back(nums[i]);
11         }
12     }
13 
14     void update(int i, int val) 
15     {
16         int diff = val - values[i];
17         for (int k = i + 1; k < sums.size(); k++)
18             sums[k] = sums[k] + diff;
19         values[i] = val;
20     }
21 
22     int sumRange(int i, int j) 
23     {
24         return sums[j + 1] - sums[i];
25     }
26 private:
27     vector<int> sums;
28     vector<int> values;
29 };

 

转载于:https://www.cnblogs.com/msymm/p/8278251.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值