def__init__(self, nums): """ :type nums: List[int] """ self.nums = nums self.nums.insert(0, 0) # one-based self.l = len(nums) self.tree = [0for i in range(self.l)] # construct tree for i in range(1, self.l + 1): start = i while start < len(self.tree): self.tree[start] += self.nums[i] start += self.lowbit(start)
deflowbit(self, x): return x & -x
defupdate(self, i, val): """ :type i: int :type val: int :rtype: void """ start = i + 1 diff = val - self.nums[start] while start < len(self.tree): self.tree[start] += diff start += self.lowbit(start) self.nums[i + 1] = val
defsumRange(self, i, j): """ :type i: int :type j: int :rtype: int """ # inclusive [, ] defsum_start(n): ans = 0 while n != 0: ans += self.tree[n] n -= self.lowbit(n) return ans # make it one based return sum_start(j + 1) - sum_start(i)