前缀和
暴力解法
class NumArray:
def __init__(self, nums: List[int]):
self.lst = nums
def sumRange(self, i: int, j: int) -> int:
return sum(self.lst[i:j+1])
# Your NumArray object will be instantiated and called as such:
# obj = NumArray(nums)
# param_1 = obj.sumRange(i,j)
前缀和
class NumArray:
def __init__(self, nums: List[int]):
self.lst = nums
self.pre = [0]
for i in range(1,len(self.lst)+1):
self.pre.append(self.pre[i-1] + self.lst[i-1])
def sumRange(self, i: int, j: int) -> int:
return self.pre[j+1] - self.pre[i]
# Your NumArray object will be instantiated and called as such:
# obj = NumArray(nums)
# param_1 = obj.sumRange(i,j)
区别