classNumArray(object): def__init__(self, nums): """ initialize your data structure here. :type nums: List[int] """ self.sum_array = [0] * (len(nums) + 1) self.nums = nums self.n = len(nums) for i in xrange(len(nums)): self.add(i + 1,nums[i])
defadd(self,x,val): while x <= self.n: self.sum_array[x] += val x += self.lowbit(x)
deflowbit(self,x): return x & -x
defsum(self,x): res = 0 while x >0: res += self.sum_array[x] x -= self.lowbit(x) return res
defupdate(self, i, val): """ :type i: int :type val: int :rtype: int """ self.add(i + 1, val - self.nums[i]) self.nums[i] = val
defsumRange(self, i, j): """ sum of elements nums[i..j], inclusive. :type i: int :type j: int :rtype: int """ ifnot self.nums: return0 return self.sum(j+1) - self.sum(i)