题目
给定一个整数数组 nums,求出数组从索引 i 到 j (i ≤ j) 范围内元素的总和,包含 i, j 两点。
链接:https://leetcode.com/problems/range-sum-query-immutable/
Given an integer array nums, find the sum of the elements between indices i and j (i ≤ j), inclusive.
Note:
- You may assume that the array does not change.
- There are many calls to sumRange function.
Example:
Given nums = [-2, 0, 3, -5, 2, -1]
sumRange(0, 2) -> 1
sumRange(2, 5) -> -1
sumRange(0, 5) -> -3
思路及代码
DP
- sumlist[i] = nums[0] + nums[1] +……+nums[i]
- sumRange[i,j] = sumlist[j] - sumlist[i-1]
- 初始值:sumlist[0] = nums[0], sumlist[1] = nums[0] + nums[1]
class NumArray:
def __init__(self, nums: List[int]):
self.nums = nums
self.sumlist = []
n = len(nums)
if n == 0:
return
if n == 1:
self.sumlist.append(nums[0])
return
if n > 1:
self.sumlist.append(nums[0])
self.sumlist.append(nums[1]+nums[0])
for i in range(2, n):
self.sumlist.append(self.sumlist[i-1] + nums[i])
def sumRange(self, i: int, j: int) -> int:
if i > 0:
return self.sumlist[j] - self.sumlist[i-1]
else:
return self.sumlist[j]
复杂度
T =
O
(
n
)
O(n)
O(n)
S =
O
(
n
)
O(n)
O(n)