树状数组复习 leetcode 307

来源:互联网 发布:cisco 端口turnk配置 编辑:程序博客网 时间:2024/06/14 03:15

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) -> 9update(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是数组下标加一的}




0 0
原创粉丝点击