树状数组(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;
}
}