Python 官方文档:入门教程 => 点击学习
目录题目描述思路分析AC 代码题目描述 原题链接 : 303. 区域和检索 给定一个整数数组 nums,处理以下类型的多个查询: 计算索引 left&nbs
原题链接 :
303. 区域和检索
给定一个整数数组 nums,处理以下类型的多个查询:
实现 NumArray 类:
示例 1:
输入:
["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))
提示:
1 <= nums.length <= 10^4
-10^5 <= nums[i] <= 10^5
0 <= i <= j < nums.length
最多调用 10^4 次 sumRange 方法
如果sumRange方法只调用一次的话,很简单,使用暴力求解的方式,时间复杂度为O(n),如果sumRange方法被多次调用的话,那么便不能使用暴力求解的方式,因为时间复杂度会达到O(n^2),使用动态规划的方式进行求解。
建立一个数组dp, 用于存储前面所有数到当前数字的和,例如数组为[1, 2, 3, 4],则dp = [1, 3, 6, 10];
在sumRange函数中定义求解方式。以[1, 2, 3, 4]数组为例,如果[I, j] = [0, 2], 则要求的结果为res = 6 = 1 + 2 + 3,而对应于dp中的数,res = dp[2] – 0,若[I, j ] = [1, 3], 则res = 9 = 2 + 3 + 4 = dp[3] – dp[0] = 10 – 1 = 9, 因此可以由此推断出求解公式: res = dp[j], if i =0 ; res = dp[j] - dp[i-1], if i > 0
class NumArray:
def __init__(self, nums: List[int]):
self.dp = []
if len(nums) == 0:
return
self.dp.append(nums[0])
for i in range(1, len(nums)):
self.dp.append(self.dp[i-1] + nums[i])
def sumRange(self, i: int, j: int) -> int:
if i == 0:
return self.dp[j]
else:
return self.dp[j] - self.dp[i - 1]
# Your NumArray object will be instantiated and called as such:
# obj = NumArray(nums)
# param_1 = obj.sumRange(i,j)
以上就是python题解LeetCode303区域和检索示例详解的详细内容,更多关于Python题解区域检索的资料请关注编程网其它相关文章!
--结束END--
本文标题: python题解LeetCode303区域和检索示例详解
本文链接: https://www.lsjlt.com/news/176348.html(转载时请注明来源链接)
有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341
下载Word文档到电脑,方便收藏和打印~
2024-03-01
2024-03-01
2024-03-01
2024-02-29
2024-02-29
2024-02-29
2024-02-29
2024-02-29
2024-02-29
2024-02-29
回答
回答
回答
回答
回答
回答
回答
回答
回答
回答
0