解题思路
以 nums = [-2, 0, 3, -5, 2, -1]
为例
- 第一步先制定一个列表,元素是前n项元素的和
list = [0, -2, -2, 1, -4, -2, -3]
,首项除外 - 第二步求
(i,j)
的总和,即list[j+1]-list[i]
代码
class NumArray(object): def __init__(self, nums): """ :type nums: List[int] """ self.nums = nums self.list = [0] for i in range(0,len(self.nums)): self.list.append(self.nums[i]+self.list[i]) def sumRange(self, i, j): """ :type i: int :type j: int :rtype: int """ return (self.list[j+1]-self.list[i]) # Your NumArray object will be instantiated and called as such: # obj = NumArray(nums) # param_1 = obj.sumRange(i,j)