LeetCode 题解工作台
标记所有下标的最早秒数 II
给你两个下标从 1 开始的整数数组 nums 和 changeIndices ,数组的长度分别为 n 和 m 。 一开始, nums 中所有下标都是未标记的,你的任务是标记 nums 中 所有 下标。 从第 1 秒到第 m 秒( 包括 第 m 秒),对于每一秒 s ,你可以执行以下操作 之一 : 选…
4
题型
0
代码语言
3
相关题
当前训练重点
困难 · 二分·搜索·答案·空间
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 二分·搜索·答案·空间 题型思路
题目描述
给你两个下标从 1 开始的整数数组 nums 和 changeIndices ,数组的长度分别为 n 和 m 。
一开始,nums 中所有下标都是未标记的,你的任务是标记 nums 中 所有 下标。
从第 1 秒到第 m 秒(包括 第 m 秒),对于每一秒 s ,你可以执行以下操作 之一 :
- 选择范围
[1, n]中的一个下标i,并且将nums[i]减少1。 - 将
nums[changeIndices[s]]设置成任意的 非负 整数。 - 选择范围
[1, n]中的一个下标i, 满足nums[i]等于0, 并 标记 下标i。 - 什么也不做。
请你返回范围 [1, m] 中的一个整数,表示最优操作下,标记 nums 中 所有 下标的 最早秒数 ,如果无法标记所有下标,返回 -1 。
示例 1:
输入:nums = [3,2,3], changeIndices = [1,3,2,2,2,2,3] 输出:6 解释:这个例子中,我们总共有 7 秒。按照以下操作标记所有下标: 第 1 秒:将 nums[changeIndices[1]] 变为 0 。nums 变为 [0,2,3] 。 第 2 秒:将 nums[changeIndices[2]] 变为 0 。nums 变为 [0,2,0] 。 第 3 秒:将 nums[changeIndices[3]] 变为 0 。nums 变为 [0,0,0] 。 第 4 秒:标记下标 1 ,因为 nums[1] 等于 0 。 第 5 秒:标记下标 2 ,因为 nums[2] 等于 0 。 第 6 秒:标记下标 3 ,因为 nums[3] 等于 0 。 现在所有下标已被标记。 最早可以在第 6 秒标记所有下标。 所以答案是 6 。
示例 2:
输入:nums = [0,0,1,2], changeIndices = [1,2,1,2,1,2,1,2] 输出:7 解释:这个例子中,我们总共有 8 秒。按照以下操作标记所有下标: 第 1 秒:标记下标 1 ,因为 nums[1] 等于 0 。 第 2 秒:标记下标 2 ,因为 nums[2] 等于 0 。 第 3 秒:将 nums[4] 减少 1 。nums 变为 [0,0,1,1] 。 第 4 秒:将 nums[4] 减少 1 。nums 变为 [0,0,1,0] 。 第 5 秒:将 nums[3] 减少 1 。nums 变为 [0,0,0,0] 。 第 6 秒:标记下标 3 ,因为 nums[3] 等于 0 。 第 7 秒:标记下标 4 ,因为 nums[4] 等于 0 。 现在所有下标已被标记。 最早可以在第 7 秒标记所有下标。 所以答案是 7 。
示例 3:
输入:nums = [1,2,3], changeIndices = [1,2,3] 输出:-1 解释:这个例子中,无法标记所有下标,因为我们没有足够的秒数。 所以答案是 -1 。
提示:
1 <= n == nums.length <= 50000 <= nums[i] <= 1091 <= m == changeIndices.length <= 50001 <= changeIndices[i] <= n
解题思路
方法一
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | Depends on the final approach |
| 空间 | Depends on the final approach |
面试官常问的追问
外企场景- question_mark
The candidate demonstrates understanding of binary search over a valid answer space.
- question_mark
The candidate effectively simulates the marking process within the time bounds.
- question_mark
The candidate uses a greedy strategy when choosing which indices to mark first.
常见陷阱
外企场景- error
Not considering the binary search space's bounds correctly (n to sum(nums[i]) + n).
- error
Failing to account for the exact operations in the problem when simulating the seconds.
- error
Misinterpreting the constraints, which can lead to trying to mark indices without enough time.
进阶变体
外企场景- arrow_right_alt
Consider how the problem changes with larger arrays or different time constraints.
- arrow_right_alt
Test cases with very large values for nums[i] and check efficiency.
- arrow_right_alt
What happens when the nums array has only 1 or 2 elements?