树状数组 BIT

树状数组(Binary Indexed Tree(B.I.T), Fenwick Tree)是一个查询和修改复杂度都为log(n)的数据结构。主要用于查询任意两位之间的所有元素之和,但是每次只能修改一个元素的值;经过简单修改可以在log(n)的复杂度下进行范围修改,但是这时只能查询其中一个元素的值(如果加入多个辅助数组则可以实现区间修改与区间查询)。
这种数据结构(算法)并没有C++和Java的库支持,需要自己手动实现。在Competitive Programming的竞赛中被广泛的使用。树状数组和线段树很像,但能用树状数组解决的问题,基本上都能用线段树解决,而线段树能解决的树状数组不一定能解决。相比较而言,树状数组效率要高很多。

LeetCode307. Range Sum Query - Mutable
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.

下面给出JAVA代码:

class NumArray {
        public int []a,bit;
        public NumArray(int[] nums) {
            a = nums.clone();
            bit = new int[a.length+1];
            for(int i = 1;i <= a.length; i++){
                int k = i;
                while (k <= a.length){
                    bit[k] += a[i-1];
                    k += k & -k;
                }
            }
        }

        public void update(int i, int val) {
            int ret = val - a[i];
            int k = i + 1;
            while (k <= a.length){
                bit[k] += ret;
                k += k & -k;
            }
            a[i] = val;
        }

        public int sumRange(int i, int j) {
            int result1 = 0,result2 = 0;
            int k = i;
            while (k > 0){
                result1 += bit[k];
                k -= k & -k;
            }
            k = j + 1;
            while (k > 0){
                result2 += bit[k];
                k -= k & -k;
            }
            //System.out.println(result2 - result1);
            return result2 - result1;
        }
    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值