描述
给定一个整数数组 nums,处理以下类型的多个查询:
- 计算索引 left 和 right (包含 left 和 right)之间的 nums 元素的 和 ,其中 left <= right
实现 NumArray 类:
- NumArray(int[] nums) 使用数组 nums 初始化对象
-
int sumRange(int i, int j) 返回数组 nums 中索引 left 和 right 之间的元素的 总和 ,包含 left 和 right 两点(也就是 nums[left] + nums[left + 1] + ... + nums[right] )
思路
前缀和
Code
- python3 | Time Limit Exceeded
class NumArray:
def __init__(self, nums):
self.mnums = nums
def sumRange(self, left: int, right: int) -> int:
preNums = [0]
i = 0
print(len(self.mnums))
print("#################################")
#构造前缀和
while i < len(self.mnums) - 1:
print(self.mnums[i])
preNums.append(preNums[i] + self.mnums[i])
i += 1
print("#################################")
print(preNums)
print("#################################")
print(preNums[right + 1])
print(preNums[left])
return (preNums[right+1] - preNums[left])
# Your NumArray object will be instantiated and called as such:
nums = [1,2,3,4,5,6]
obj = NumArray(nums)
param_1 = obj.sumRange(0,3)
print("#################################")
print(param_1)
- python3 | Accepted
说实话有点疑惑为啥下面这个可以通过
class NumArray:
def __init__(self, nums: List[int]):
self.mnums = nums
self.preNums = [0]
i = 0
while i < len(self.mnums):
self.preNums.append(self.preNums[i] + self.mnums[i])
i += 1
def sumRange(self, left: int, right: int) -> int:
# preNums = [0]
# i = 0
# while i < len(self.mnums):
# preNums.append(preNums[i] + self.mnums[i])
# i += 1
return self.preNums[right+1] - self.preNums[left]
# Your NumArray object will be instantiated and called as such:
# obj = NumArray(nums)
# param_1 = obj.sumRange(left,right)