# leetcode刷题：303. 区域和检索 - 数组不可变

in hive-180932 •  7 months ago

NumArray(int[] nums) 使用数组 nums 初始化对象
int sumRange(int i, int j) 返回数组 nums 从索引 i 到 j（i ≤ j）范围内元素的总和，包含 i、j 两点（也就是 sum(nums[i], nums[i + 1], ... , nums[j])）

["NumArray", "sumRange", "sumRange", "sumRange"]
[[[-2, 0, 3, -5, 2, -1]], [0, 2], [2, 5], [0, 5]]

[null, 1, -1, -3]

NumArray numArray = new NumArray([-2, 0, 3, -5, 2, -1]);
numArray.sumRange(0, 2); // return 1 ((-2) + 0 + 3)
numArray.sumRange(2, 5); // return -1 (3 + (-5) + 2 + (-1))
numArray.sumRange(0, 5); // return -3 ((-2) + 0 + 3 + (-5) + 2 + (-1))

``````class NumArray:
def __init__(self, nums: List[int]):
self.nums = nums
def sumRange(self, i: int, j: int) -> int:
return sum(self.nums[i:j+1])
``````

``````class NumArray:
def __init__(self, nums: List[int]):
self.num_sum = [0]
for i in range(len(nums)):
self.num_sum.append(self.num_sum[i]+nums[i])
def sumRange(self, i: int, j: int) -> int:
return self.num_sum[j+1] - self.num_sum[i]
``````

Sort Order:
·  7 months ago