题目描述
Given an integer array nums, find the sum of the elements between indices i and j (i ≤ j), inclusive.
Example:
Given nums = [-2, 0, 3, -5, 2, -1] sumRange(0, 2) -> 1 sumRange(2, 5) -> -1 sumRange(0, 5) -> -3
一道水题,主要就是注意一下效率。用暴力解法是会time limit exception的。
class NumArray:
def __init__(self, nums):
"""
:type nums: List[int]
"""
self.arr = nums
for i in range(1,len(nums)):
self.arr[i] += self.arr[i-1]
def sumRange(self, i, j):
"""
:type i: int
:type j: int
:rtype: int """
if i==0:
return self.arr[j]
else:
return self.arr[j] - self.arr[i-1]
# Your NumArray object will be instantiated and called as such:
# obj = NumArray(nums)
# param_1 = obj.sumRange(i,j)
没有什么需要解释和记录的地方。
之前刷题一直想着要让代码更简短,但是其实应该更追求效率。