LeetCode 题解工作台
任务调度器 II
给你一个下标从 0 开始的正整数数组 tasks ,表示需要 按顺序 完成的任务,其中 tasks[i] 表示第 i 件任务的 类型 。 同时给你一个正整数 space ,表示一个任务完成 后 ,另一个 相同 类型任务完成前需要间隔的 最少 天数。 在所有任务完成前的每一天,你都必须进行以下两种操作…
3
题型
5
代码语言
3
相关题
当前训练重点
中等 · 数组·哈希·扫描
答案摘要
我们可以用哈希表 记录每个任务下一次可以被执行的时间,初始时 中的所有值都为 ,用变量 记录当前时间。 遍历数组 ,对于每个任务 ,当前时间 加一,表示从上一次执行任务到现在已经过去了一天,如果此时 $day[task] \gt ans$,说明任务 需要在第 天才能被执行,因此我们更新当前时间 $ans = \max(ans, day[task])$。然后更新 的值为 $ans + …
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 数组·哈希·扫描 题型思路
题目描述
给你一个下标从 0 开始的正整数数组 tasks ,表示需要 按顺序 完成的任务,其中 tasks[i] 表示第 i 件任务的 类型 。
同时给你一个正整数 space ,表示一个任务完成 后 ,另一个 相同 类型任务完成前需要间隔的 最少 天数。
在所有任务完成前的每一天,你都必须进行以下两种操作中的一种:
- 完成
tasks中的下一个任务 - 休息一天
请你返回完成所有任务所需的 最少 天数。
示例 1:
输入:tasks = [1,2,1,2,3,1], space = 3 输出:9 解释: 9 天完成所有任务的一种方法是: 第 1 天:完成任务 0 。 第 2 天:完成任务 1 。 第 3 天:休息。 第 4 天:休息。 第 5 天:完成任务 2 。 第 6 天:完成任务 3 。 第 7 天:休息。 第 8 天:完成任务 4 。 第 9 天:完成任务 5 。 可以证明无法少于 9 天完成所有任务。
示例 2:
输入:tasks = [5,8,8,5], space = 2 输出:6 解释: 6 天完成所有任务的一种方法是: 第 1 天:完成任务 0 。 第 2 天:完成任务 1 。 第 3 天:休息。 第 4 天:休息。 第 5 天:完成任务 2 。 第 6 天:完成任务 3 。 可以证明无法少于 6 天完成所有任务。
提示:
1 <= tasks.length <= 1051 <= tasks[i] <= 1091 <= space <= tasks.length
解题思路
方法一:哈希表 + 模拟
我们可以用哈希表 记录每个任务下一次可以被执行的时间,初始时 中的所有值都为 ,用变量 记录当前时间。
遍历数组 ,对于每个任务 ,当前时间 加一,表示从上一次执行任务到现在已经过去了一天,如果此时 ,说明任务 需要在第 天才能被执行,因此我们更新当前时间 。然后更新 的值为 ,表示任务 下一次可以被执行的时间为 。
遍历结束后,将 返回即可。
时间复杂度 ,空间复杂度 。其中 为数组 的长度。
class Solution:
def taskSchedulerII(self, tasks: List[int], space: int) -> int:
day = defaultdict(int)
ans = 0
for task in tasks:
ans += 1
ans = max(ans, day[task])
day[task] = ans + space + 1
return ans
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | Depends on the final approach |
| 空间 | Depends on the final approach |
面试官常问的追问
外企场景- question_mark
Look for the candidate's ability to optimize task scheduling by minimizing break days.
- question_mark
Evaluate their understanding of hash map operations and how it ties into scheduling tasks efficiently.
- question_mark
Assess their ability to handle edge cases, such as tasks with large gaps or very small space constraints.
常见陷阱
外企场景- error
Failing to correctly handle the spacing constraint by not taking breaks at the optimal times.
- error
Overcomplicating the solution with unnecessary nested loops or excessive time complexity.
- error
Misunderstanding the nature of breaks and underestimating the importance of placing them strategically.
进阶变体
外企场景- arrow_right_alt
What if the space constraint varies between different tasks? This could require a more complex strategy to handle multiple constraints.
- arrow_right_alt
Consider what happens if tasks are already spaced appropriately. This could result in fewer breaks or days.
- arrow_right_alt
What if there are only one or two types of tasks? This could simplify the problem, as fewer space checks are needed.