树状数组复习 leetcode 307
阅读原文时间:2023年09月06日阅读:1

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:

一般的查找范围和时间复杂度为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是数组下标加一的
}

手机扫一扫

移动阅读更方便

阿里云服务器
腾讯云服务器
七牛云服务器

你可能感兴趣的文章