线段树数组实现的逻辑比较复杂......借此记录一下吧😭

class NumArray {
int[] tree;
int n;
public NumArray(int[] nums) {
n = nums.length;
// 非叶子节点个数为叶子结点个数+1,所以是n*2
tree = new int[n * 2];
// 初始化数组,都放在最后
for(int i = n; i < 2*n; i++){
tree[i] = nums[i-n];
}
// 初始化数据前面的节点值
for(int i = n-1; i >= 0; i--){
tree[i] = tree[i*2] + tree[i*2+1];
}
}
public void update(int i, int val) {
// 找到索引在数组中的位置
int pos = n + i;
// 修改数据
tree[pos] = val;
// 修改节点前面与它有关的节点的值
while(pos > 0){
int left = pos%2==0? pos: pos-1;
int right = pos%2==0? pos+1: pos;
tree[pos/2] = tree[left] + tree[right];
pos /= 2;
}
}
public int sumRange(int i, int j) {
int sum = 0;
int l = n + i;
int r = n + j;
while(r >= l){
if(l % 2 == 1){
sum += tree[l];
l++;
}
if(r % 2 == 0){
sum += tree[r];
r--;
}
l /= 2;
r /= 2;
}
return sum;
}
}
/**
* Your NumArray object will be instantiated and called as such:
* NumArray obj = new NumArray(nums);
* obj.update(i,val);
* int param_2 = obj.sumRange(i,j);
*/
152

被折叠的 条评论
为什么被折叠?



