/**
* @author xnl
* @Description:
* @date: 2022/6/21 21:41
*/
public class Solution {
public static void main(String[] args) {
int[] arr = {-2, 0, 3, -5, 2, -1};
NumArray numArray = new NumArray(arr);
System.out.println(numArray.sumRange(0 ,2));
}
}
class NumArray {
int[] tree;
int[] data;
public NumArray(int[] nums) {
this.data = nums;
this.tree = new int[nums.length * 4];
buildTree(0, 0, data.length - 1);
}
private void buildTree(int treeIndex, int l, int r){
if (l == r){
tree[treeIndex] = data[l];
return;
}
int mid = l + (r - l) / 2;
int left = treeIndex * 2 + 1;
int right = treeIndex * 2 + 2;
buildTree(left, l ,mid);
buildTree(right, mid + 1, r);
tree[treeIndex] = tree[left] + tree[right];
}
private int query(int treeIndex, int l, int r, int queryL, int queryR){
if (l == queryL && r == queryR ){
return tree[treeIndex];
}
int mid = l + (r - l) / 2;
int left = treeIndex * 2 + 1;
int right = treeIndex * 2 + 2;
// 在左边界大于中间节点,往右边查找
if (queryL > mid){
return query(right, mid + 1, r, queryL, queryR);
}
if (queryR <= mid){
return query(left, l, mid, queryL, queryR);
}
int leftResult = query(left, l ,mid, queryL, mid);
int rightResult = query(right, mid + 1, r, mid + 1, queryR);
return leftResult + rightResult;
}
public int sumRange(int left, int right) {
return query(0, 0, data.length - 1, left, right);
}
}
03-01
149
![](https://csdnimg.cn/release/blogv2/dist/pc/img/readCountWhite.png)
01-31
116
![](https://csdnimg.cn/release/blogv2/dist/pc/img/readCountWhite.png)