LeetCode 题解工作台
区域和检索 - 数组不可变
给定一个整数数组 nums ,处理以下类型的多个查询: 计算索引 left 和 right (包含 left 和 right )之间的 nums 元素的 和 ,其中 left 实现 NumArray 类: NumArray(int[] nums) 使用数组 nums 初始化对象 int sumRan…
3
题型
10
代码语言
3
相关题
当前训练重点
简单 · 前缀和
答案摘要
我们创建一个长度为 $n + 1$ 的前缀和数组 ,其中 表示前 个元素的前缀和,即 $s[i] = \sum_{j=0}^{i-1} nums[j]$,那么索引 $[left, right]$ 之间的元素的和就可以表示为 $s[right + 1] - s[left]$。 初始化前缀和数组 的时间复杂度为 ,查询的时间复杂度为 。空间复杂度 。
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 前缀和 题型思路
题目描述
给定一个整数数组 nums,处理以下类型的多个查询:
- 计算索引
left和right(包含left和right)之间的nums元素的 和 ,其中left <= right
实现 NumArray 类:
NumArray(int[] nums)使用数组nums初始化对象int sumRange(int left, int right)返回数组nums中索引left和right之间的元素的 总和 ,包含left和right两点(也就是nums[left] + nums[left + 1] + ... + nums[right])
示例 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 <= 104-105 <= nums[i] <= 1050 <= left <= right < nums.length- 最多调用
104次sumRange方法
解题思路
方法一:前缀和
我们创建一个长度为 的前缀和数组 ,其中 表示前 个元素的前缀和,即 ,那么索引 之间的元素的和就可以表示为 。
初始化前缀和数组 的时间复杂度为 ,查询的时间复杂度为 。空间复杂度 。
class NumArray:
def __init__(self, nums: List[int]):
self.s = list(accumulate(nums, initial=0))
def sumRange(self, left: int, right: int) -> int:
return self.s[right + 1] - self.s[left]
# Your NumArray object will be instantiated and called as such:
# obj = NumArray(nums)
# param_1 = obj.sumRange(left,right)
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | Depends on the final approach |
| 空间 | Depends on the final approach |
面试官常问的追问
外企场景- question_mark
Understanding the trade-off between preprocessing and query time is crucial.
- question_mark
Candidates should demonstrate an ability to optimize for multiple queries.
- question_mark
Pay attention to how the solution scales with large inputs.
常见陷阱
外企场景- error
Not optimizing for multiple queries by recalculating sums from scratch.
- error
Incorrectly calculating the range sum due to off-by-one errors with indices.
- error
Failing to properly initialize the prefix sum array, leading to incorrect query results.
进阶变体
外企场景- arrow_right_alt
Query sum over a segment of the array after each update.
- arrow_right_alt
Handle range queries with modifications to the array in between.
- arrow_right_alt
Designing a solution for a multi-dimensional range sum query.