一、
class NumArray:
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)
1.sum函数:
二、
class NumArray(object):
def __init__(self, nums):
"""
:type nums: List[int]
"""
self._dp=[0]*len(nums)
sum=0
for i in range(len(nums)):
sum+=nums[i]
self._dp[i]=sum
def sumRange(self, i, j):
"""
:type i: int
:type j: int
:rtype: int
"""
if(i==0):
return self._dp[j]
else:
return self._dp[j]-self._dp[i-1]
# Your NumArray object will be instantiated and called as such:
# obj = NumArray(nums)
# param_1 = obj.sumRange(i,j)
1._var ;变量名前一个下划线来定义,此变量为保护成员protected,只有类及其子类可以访问。此变量不能通过from XXX import xxx 导入
__var;变量名前两个下划线来定义,此变量为私有private,只允许类本身访问,连子类都不可以访问。