462python
769數組
Favoritebash
Share Given an integer array nums, find the sum of the elements between indices i and j (i ≤ j), inclusive.ui
Example: Given nums = [-2, 0, 3, -5, 2, -1]spa
sumRange(0, 2) -> 1 sumRange(2, 5) -> -1 sumRange(0, 5) -> -3 Note: You may assume that the array does not change. There are many calls to sumRange function.code
思路:用數組dp記錄前n位的和,sumRange(i,j)即爲計算dp[j]-dp[i-1]的值,注意i爲0的狀況element
代碼:python3it
class NumArray:
def __init__(self, nums: List[int]):
self.dp=nums
for i in range(len(nums)):
if i==0:
self.dp[i]=nums[i]
else:
self.dp[i]=self.dp[i-1]+nums[i]
def sumRange(self, i: int, j: int) -> int:
if i==0:
return self.dp[j]
return self.dp[j]-self.dp[i-1]
複製代碼