1. 题目
https://leetcode-cn.com/problems/range-sum-query-immutable/submissions/
给定一个整数数组 nums
,求出数组从索引 i
到 j (i ≤ j)
范围内元素的总和,包含 i
, j
两点。
示例:
给定 nums = [-2, 0, 3, -5, 2, -1],求和函数为 sumRange()
sumRange(0, 2) -> 1
sumRange(2, 5) -> -1
sumRange(0, 5) -> -3
说明:
- 你可以假设数组不可变
- 会多次调用 sumRange 方法
2. 我的AC
方法一
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
self.sums = []
temp_sum = 0
for num in nums:
temp_sum += num
self.sums.append(temp_sum)
def sumRange(self, i, j):
"""
:type i: int
:type j: int
:rtype: int
"""
if i == 0:
return self.sums[j]
else:
return self.sums[j] - self.sums[i-1]
3. 小结
- 出错点:注意索引
i == 0
,列表的索引特别要注意是正是负