leetcode_303. 区域和检索 - 数组不可变
目录
一、题目内容
给定一个整数数组 nums,求出数组从索引 i 到 j(i ≤ j)范围内元素的总和,包含 i、j 两点。
实现 NumArray 类:
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))
提示:
0 <= nums.length <= 10^4
-105 <= nums[i] <= 10^5
0 <= i <= j < nums.length
最多调用 104 次 sumRange 方法
二、解题思路
1.暴力法,每次都从i到j计算和;
2.动态规划,计算从左边起始到每个元素的和,当前和=到之前数字的和+当前数字;
三、代码
-
class NumArray1:
-
-
def __init__(self, nums: list):
-
self.nums = nums
-
-
def sumRange(self, i: int, j: int) -> int:
-
return sum(self.nums[i:j + 1])
-
-
-
class NumArray2:
-
-
def __init__(self, nums: list):
-
self.nums = nums
-
self.sums = [0 for _ in range(len(nums) + 1)]
-
-
for i in range(len(nums)):
-
self.sums[i + 1] = self.sums[i] + nums[i]
-
-
def sumRange(self, i: int, j: int) -> int:
-
return self.sums[j + 1] - self.sums[i]
-
-
-
# Your NumArray object will be instantiated and called as such:
-
# obj = NumArray(nums)
-
# param_1 = obj.sumRange(i,j)
-
-
if __name__ == '__main__':
-
nums = [-2, 0, 3, -5, 2, -1]
-
numArray = NumArray2(nums)
-
ans1 = numArray.sumRange(0, 2)
-
ans2 = numArray.sumRange(2, 5)
-
ans3 = numArray.sumRange(0, 5)
-
print(ans1)
-
print(ans2)
-
print(ans3)
文章来源: nickhuang1996.blog.csdn.net,作者:悲恋花丶无心之人,版权归原作者所有,如需转载,请联系作者。
原文链接:nickhuang1996.blog.csdn.net/article/details/114253915
- 点赞
- 收藏
- 关注作者
评论(0)