分段树算法 (leetcode 307 python)
题目:给定一个整数数组 nums,求出数组从索引 i 到 j (i ≤ j) 范围内元素的总和,包含 i, j 两点。
update(i, val) 函数可以通过将下标为 i 的数值更新为 val,从而对数列进行修改。
示例:
Given nums = [1, 3, 5] sumRange(0, 2) -> 9 update(1, 2) sumRange(0, 2) -> 8
说明:
- 数组仅可以在 update 函数下进行修改。
- 你可以假设 update 函数与 sumRange 函数的调用次数是均匀分布的。
__author__ = "那位先生Beer" class NumArray( object ): def __init__( self, nums ): self.l = len( nums ) self.nums = [0] * self.l for i in nums: self.nums.append( i ) i = self.l - 1 while (i > 0): self.nums[i] = self.nums[2 * i] + self.nums[2 * i + 1] i -= 1 def update( self, i, val ): i += self.l diff = val - self.nums[i] while (i > 0): self.nums[i] += diff i //= 2 def sumRange( self, i, j ): sum = 0 i += self.l j += self.l while (i <= j): if i % 2 == 1: sum += self.nums[i] i += 1 if j % 2 == 0: sum += self.nums[j] j -= 1 i = i // 2 j = j // 2 return sum # Your NumArray object will be instantiated and called as such: # obj = NumArray(nums) # obj.update(i,val) # param_2 = obj.sumRange(i,j)