LeetCode 题解工作台
零数组变换 I
给定一个长度为 n 的整数数组 nums 和一个二维数组 queries ,其中 queries[i] = [l i , r i ] 。 对于每个查询 queries[i] : 在 nums 的下标范围 [l i , r i ] 内选择一个下标 子集 。 将选中的每个下标对应的元素值减 1。 零数组…
2
题型
5
代码语言
3
相关题
当前训练重点
中等 · 前缀和
答案摘要
我们可以使用差分数组来解决这个问题。 定义一个长度为 $n + 1$ 的数组 ,初始值全部为 。对于每个查询 $[l, r]$,我们将 加 ,将 $d[r + 1]$ 减 。
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 前缀和 题型思路
题目描述
给定一个长度为 n 的整数数组 nums 和一个二维数组 queries,其中 queries[i] = [li, ri]。
对于每个查询 queries[i]:
- 在
nums的下标范围[li, ri]内选择一个下标 子集。 - 将选中的每个下标对应的元素值减 1。
零数组 是指所有元素都等于 0 的数组。
如果在按顺序处理所有查询后,可以将 nums 转换为 零数组 ,则返回 true,否则返回 false。
示例 1:
输入: nums = [1,0,1], queries = [[0,2]]
输出: true
解释:
- 对于 i = 0:
- 选择下标子集
[0, 2]并将这些下标处的值减 1。 - 数组将变为
[0, 0, 0],这是一个零数组。
- 选择下标子集
示例 2:
输入: nums = [4,3,2,1], queries = [[1,3],[0,2]]
输出: false
解释:
- 对于 i = 0:
- 选择下标子集
[1, 2, 3]并将这些下标处的值减 1。 - 数组将变为
[4, 2, 1, 0]。
- 选择下标子集
- 对于 i = 1:
- 选择下标子集
[0, 1, 2]并将这些下标处的值减 1。 - 数组将变为
[3, 1, 0, 0],这不是一个零数组。
- 选择下标子集
提示:
1 <= nums.length <= 1050 <= nums[i] <= 1051 <= queries.length <= 105queries[i].length == 20 <= li <= ri < nums.length
解题思路
方法一:差分数组
我们可以使用差分数组来解决这个问题。
定义一个长度为 的数组 ,初始值全部为 。对于每个查询 ,我们将 加 ,将 减 。
然后我们遍历数组 在 范围内的每个元素,累加前缀和 ,如果 ,说明 不能转换为零数组,返回 。
遍历结束后,返回 。
时间复杂度 ,空间复杂度 。其中 和 分别为数组 和 的长度。
class Solution:
def isZeroArray(self, nums: List[int], queries: List[List[int]]) -> bool:
d = [0] * (len(nums) + 1)
for l, r in queries:
d[l] += 1
d[r + 1] -= 1
s = 0
for x, y in zip(nums, d):
s += y
if x > s:
return False
return True
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | complexity is O(n + m) where n is the length of nums and m is the number of queries, because each query is processed once and prefix sums are computed in a single pass. Space complexity is O(n) for the difference array. |
| 空间 | O(n) |
面试官常问的追问
外企场景- question_mark
Check whether you are correctly using a difference array instead of modifying the original array per query.
- question_mark
Make sure your prefix sum computation correctly accumulates all range operations.
- question_mark
Consider edge cases where queries overlap or cover entire array sections.
常见陷阱
外企场景- error
Updating the original array directly for each query leads to TLE for large n or m.
- error
Incorrect handling of diff[r+1] can miscalculate net effects at array boundaries.
- error
Forgetting to validate that all elements are zero after prefix sum accumulation.
进阶变体
外企场景- arrow_right_alt
Allowing queries that increment or decrement by different values, not just ±1.
- arrow_right_alt
Checking for partial zero arrays where only a subset must be zero.
- arrow_right_alt
Transforming using non-contiguous index sets instead of continuous ranges.