题目地址:
https://www.lintcode.com/problem/interval-sum-ii/description
给定一个数组,再给若干个询问,每次询问某个区间的和,或者修改数组中某个位置的数。
思路是树状数组(英文叫Binary Indexed Tree或者Fenwick Tree)。树状数组可以实现 O ( log n ) O(\log n) O(logn)时间复杂度的前缀和查询和单点修改,效率单纯的前缀和数组高(前缀和数组查询时间复杂度 O ( 1 ) O(1) O(1),但单点修改时间复杂度 O ( n ) O(n) O(n))。原理可以参考https://blog.csdn.net/qq_46105170/article/details/103870987。代码如下:
public class Solution {
class FenwickTree {
private int[] tree;
public FenwickTree(int[] A) {
// 注意,树状数组的长度要比区间长度多一位,这是因为下标为0的点是用不到的
tree = new int[A.length + 1];
for (int i = 0; i < A.length; i++) {
add(i + 1, A[i]);
}
}
// 实现在原数组的第i个数字上加上x。注意是第i个数字,在原数组里下标是i - 1
void add(int i, int x) {
while (i < tree.length) {
tree[i] += x;
i += lowbit(i);
}
}
// 返回原数组的前i个数字的和。注意是前i个数字,在原数组里下标是A[0, ..., i - 1]
long sum(int i) {
long res = 0;
while (i > 0) {
res += tree[i];
i -= lowbit(i);
}
return res;
}
int lowbit(int x) {
return x & -x;
}
}
/* you may need to use some attributes here */
private FenwickTree fenwickTree;
private int[] A;
/*
* @param A: An integer array
*/
public Solution(int[] A) {
// do intialization if necessary
fenwickTree = new FenwickTree(A);
this.A = A;
}
/*
* @param start: An integer
* @param end: An integer
* @return: The sum from start to end
*/
public long query(int start, int end) {
// write your code here
return fenwickTree.sum(end + 1) - fenwickTree.sum(start);
}
/*
* @param index: An integer
* @param value: An integer
* @return: nothing
*/
public void modify(int index, int value) {
// write your code here
fenwickTree.add(index + 1, value - A[index]);
A[index] = value;
}
}
初始化时间复杂度 O ( n log n ) O(n\log n) O(nlogn),其余操作时间复杂度 O ( log n ) O(\log n) O(logn),空间 O ( n ) O(n) O(n)。