树状数组(Fenwick Tree,也称为Binary Indexed Tree,BIT)是一种用于高效处理区间求和(或其他类似操作)的数据结构。它具有较低的内存消耗,能够在 O(log n) 的时间内更新单个元素和计算前缀和。
树状数组适用于处理动态数组中的元素累加操作,如频繁更新某个位置的值以及查询某个区间的和等情况。
以下是一个简单的 Java 实现示例,用于构建和使用树状数组:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38
| public class FenwickTree { private int[] fenwickTree;
public FenwickTree(int size) { fenwickTree = new int[size + 1]; }
public void update(int index, int value) { while (index < fenwickTree.length) { fenwickTree[index] += value; index += index & -index; } }
public int query(int index) { int sum = 0; while (index > 0) { sum += fenwickTree[index]; index -= index & -index; } return sum; }
public static void main(String[] args) { int[] input = {1, 3, 5, 7, 9, 11};
FenwickTree fenwickTree = new FenwickTree(input.length);
for (int i = 0; i < input.length; i++) { fenwickTree.update(i + 1, input[i]); }
System.out.println(fenwickTree.query(3)); System.out.println(fenwickTree.query(6)); } }
|
在上述代码中,FenwickTree
类用于实现树状数组。update
方法用于更新树状数组中的一个元素,query
方法用于查询前缀和。树状数组中的数组大小比原始数组大小多1,因为树状数组的下标从1开始。
这只是一个简单的树状数组实现示例。在实际应用中,您可能需要考虑更多的功能和优化,以满足不同的需求。