Problem : https://leetcode.com/problems/range-sum-query-mutable/
Cache accumulative sum of each element and diffs introduced by each update.
class NumArray:
def __init__(self, nums: List[int]):
self.nums = nums
self.sums = [0] * (len(nums) + 1)
for i in range(len(nums)):
self.sums[i+1] = self.sums[i] + self.nums[i]
self.diff = {}
def update(self, i: int, val: int) -> None:
self.diff[i] = val - self.nums[i]
def sumRange(self, i: int, j: int) -> int:
result = self.sums[j+1] - self.sums[i]
#print(self.nums, self.diff)
for k in self.diff.keys():
if i <= k <= j :
result += self.diff[k]
return result
# Your NumArray object will be instantiated and called as such:
# obj = NumArray(nums)
# obj.update(i,val)
# param_2 = obj.sumRange(i,j)
No comments:
Post a Comment