303. Range Sum Query - Immutable

# 描述

• 计算索引 left 和 right （包含 left 和 right）之间的 nums 元素的 和 ，其中 left <= right

• 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)

### 要不赞赏一下?

 微信 支付宝 PayPal Bitcoin

https://www.emperinter.info/2022/02/15/range-sum-query-immutable/