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

最新文章

  1. 聊天气泡 button backgroundImage uiimage 拉伸 stretchableImageWithLeftCapWidth: 方法的使用
  2. AEAI HR_v1.5.2升级说明,开源人力资源管理系统
  3. SSIS同步多个数据库
  4. WCF传输大数据的设置2
  5. 30+简约时尚的Macbook贴花
  6. 【学习笔记】【C语言】进制
  7. AnsiString和String的区别、使用
  8. [Linux] scp本地服务器和远程服务器拷贝文件
  9. 猜数字游戏,判断输入的数字与系统产生的数字是否一致(Math.random()与if嵌套循环)
  10. 为什么一点onclick按钮就提交表单?
  11. 可变,不可变类型和hash
  12. 比较器(TreeSet和优先队列,可以对里面的元素按照自己的意愿进行排序)
  13. 阿里云RDS数据库备份文件恢复到本地数据库
  14. springmvc中使用MockMvc测试controller
  15. 在CLion项目中指定不同版本的链接库
  16. php 七种数据类型介绍
  17. 【学习DIV+CSS】1. 你必须知道的三个知识
  18. leetcode 62 不同的路径
  19. [Functional Programming] Working with two functors(Applicative Functors)-- Part2 --liftAN
  20. app接口,如何保证是由app内部调用而非外部模拟post请求调用。

热门文章

  1. Session对象失效的客户端解决方法
  2. Laravel 5.4---后端数据分页和前端显示分页结果
  3. Urho3D 在Win10下编辑器崩溃的解决方案
  4. 宜人贷PaaS数据服务平台Genie:技术架构及功能
  5. Ubuntu 14.04lts安装vncserver
  6. 进程间的八种通信方式----共享内存是最快的 IPC 方式
  7. 图像处理之全景拼接---基于sift的全景图像拼接
  8. 14、AppWidget及Launcher RemoteViews
  9. EasyNVR H5无插件摄像机直播解决方案前端解析之:videojs的使用
  10. git拉取远程分支到本地分支或者创建本地新分支