题目
我的代码
class NumArray(object):
def __init__(self, nums):
"""
:type nums: List[int]
"""
self.nums=nums
def sumRange(self, i, j):
"""
:type i: int
:type j: int
:rtype: int
"""
return sum(self.nums[i:j+1])
# Your NumArray object will be instantiated and called as such:
# obj = NumArray(nums)
# param_1 = obj.sumRange(i,j)
优秀代码
在初始化的时候,把数值表都先给计算出来,提高速度。
class NumArray(object):
def __init__(self, nums):
"""
:type nums: List[int]
"""
self.nums = nums
totals = [0]
running_sum = 0
for num in nums:
running_sum += num
totals.append(running_sum)
self.totals = totals
# print(self.totals)
def sumRange(self, i, j):
"""
:type i: int
:type j: int
:rtype: int
"""
return self.totals[j+1] - self.totals[i]
# Your NumArray object will be instantiated and called as such:
# obj = NumArray(nums)
# param_1 = obj.sumRange(i,j)