Loading

树状数组复习 leetcode 307

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.
一般的查找范围和时间复杂度为O(m*n)..毫无疑问我掉坑里了,超时是必然的。。树状数组已经忘掉了
树状数组详解这位同学写的相当不错。。主要是有几个函数1.lowbit:树状数组用来做2分的。。很奇妙的x&-x方法。 2.add(pos,value)在pos位置加value   3.sum方法算0--pos位置的部分和。下面是树状数组的模板:
  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;
    }

而leetcode的这道题,显然是就在树状数组上改了改。。需要的代码如下
void update(int i, int val) {
    int b = a[i];
    int d= val - b;
    a[i] = val;
    add(i+1,d);
}

int sumRange(int i, int j) {
    return sum(j+1) - sum(i);//前面树状数组模板里的pos是数组下标加一的
}




posted @   SunStriKE  阅读(15)  评论(0编辑  收藏  举报  
编辑推荐:
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
· 一个奇形怪状的面试题:Bean中的CHM要不要加volatile?
· [.NET]调用本地 Deepseek 模型
· 一个费力不讨好的项目,让我损失了近一半的绩效!
阅读排行:
· 百万级群聊的设计实践
· 永远不要相信用户的输入:从 SQL 注入攻防看输入验证的重要性
· 全网最简单!3分钟用满血DeepSeek R1开发一款AI智能客服,零代码轻松接入微信、公众号、小程
· .NET 10 首个预览版发布,跨平台开发与性能全面提升
· 《HelloGitHub》第 107 期
点击右上角即可分享
微信分享提示