leetcode 307. Range Sum Query - Mutable(树状数组)
2024-08-24 21:04:42
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:
- The array is only modifiable by the update function.
- You may assume the number of calls to update and sumRange function is distributed evenly.
题解:树状数组最基本的用法(点更新,区间查询)。需要注意的是这里的点更新不是把点加一个值,而是完全更新一个点的值,这就需要不仅仅更新树状数组,原数组的值也应该更新,因为可能下一个还会更新这个点,那么就需要知道它之前的值是多少。
class NumArray {
public:
NumArray(vector<int> &nums) {
n = nums.size();
c=vector<int>(n+,);
a=vector<int>(n+,);
for(int i=;i<=n;i++){
update(i-,nums[i-]);
}
} int lowbit(int x){
return x&-x;
}
void update(int i, int val) {
int old = a[i+];
for(int k=i+;k<=n;k+=lowbit(k)){
c[k]-=old;
c[k]+=val;
}
a[i+]=val;
}
int sum(int x){
int s=;
while(x>){
s+=c[x];
x-=lowbit(x);
}
return s;
} int sumRange(int i, int j) {
return sum(j+)-sum(i);
} private:
int n;
vector<int>c;
vector<int>a;
}; // 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);
最新文章
- 聊天气泡 button backgroundImage uiimage 拉伸 stretchableImageWithLeftCapWidth: 方法的使用
- AEAI HR_v1.5.2升级说明,开源人力资源管理系统
- SSIS同步多个数据库
- WCF传输大数据的设置2
- 30+简约时尚的Macbook贴花
- 【学习笔记】【C语言】进制
- AnsiString和String的区别、使用
- [Linux] scp本地服务器和远程服务器拷贝文件
- 猜数字游戏,判断输入的数字与系统产生的数字是否一致(Math.random()与if嵌套循环)
- 为什么一点onclick按钮就提交表单?
- 可变,不可变类型和hash
- 比较器(TreeSet和优先队列,可以对里面的元素按照自己的意愿进行排序)
- 阿里云RDS数据库备份文件恢复到本地数据库
- springmvc中使用MockMvc测试controller
- 在CLion项目中指定不同版本的链接库
- php 七种数据类型介绍
- 【学习DIV+CSS】1. 你必须知道的三个知识
- leetcode 62 不同的路径
- [Functional Programming] Working with two functors(Applicative Functors)-- Part2 --liftAN
- app接口,如何保证是由app内部调用而非外部模拟post请求调用。