文章目录
tree数组
:Tree[i] 存储的是原本的数组中num[i - (i&-i)+1]到nums[i]的和
更新的时候,num[i[更新,逐一修改num[i+(i & -i)]
题目实战
总的代码:
class NumArray:
__slots__ = 'nums', 'tree'
def __init__(self, nums: List[int]):
n = len(nums)
# 注意,nums 是从0-n-1的下标,tree是1-n的下标
self.nums = [0] * n # 使 update 中算出的 delta = nums[i]
self.tree = [0] * (n + 1)
for i, x in enumerate(nums):
self.update(i, x)
def update(self, index: int, val: int) -> None:
delta = val - self.nums[index]
self.nums[index] = val
i = index + 1
# 注意这个+1的操作是下标的对应的操作
while i < len(self.tree):
self.tree[i] += delta
i += i & -i
def prefixSum(self, i: int) -> int:
s = 0
while i:
s += self.tree[i]
i &= i - 1 # i -= i & -i 的另一种写法
return s
def sumRange(self, left: int, right: int) -> int:
return self.prefixSum(right + 1) - self.prefixSum(left)