LeetCode 题解工作台
任务调度器
给你一个用字符数组 tasks 表示的 CPU 需要执行的任务列表,用字母 A 到 Z 表示,以及一个冷却时间 n 。每个周期或时间间隔允许完成一项任务。任务可以按任何顺序完成,但有一个限制:两个 相同种类 的任务之间必须有长度为 n 的冷却时间。 返回完成所有任务所需要的 最短时间间隔 。 示例 …
6
题型
5
代码语言
3
相关题
当前训练重点
中等 · 数组·哈希·扫描
答案摘要
不妨设 是任务的个数,统计每种任务出现的次数,记录在数组 `cnt` 中。 假设出现次数最多的任务为 `A`,出现次数为 ,则至少需要 $(x-1)\times(n+1) + 1$ 个时间单位才能安排完所有任务。如果出现次数最多的任务有 个,则需要再加上出现次数最多的任务的个数。
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 数组·哈希·扫描 题型思路
题目描述
给你一个用字符数组 tasks 表示的 CPU 需要执行的任务列表,用字母 A 到 Z 表示,以及一个冷却时间 n。每个周期或时间间隔允许完成一项任务。任务可以按任何顺序完成,但有一个限制:两个 相同种类 的任务之间必须有长度为 n 的冷却时间。
返回完成所有任务所需要的 最短时间间隔 。
示例 1:
示例 2:
输入:tasks = ["A","C","A","B","D","B"], n = 1
输出:6
解释:一种可能的序列是:A -> B -> C -> D -> A -> B。
由于冷却间隔为 1,你可以在完成另一个任务后重复执行这个任务。
示例 3:
提示:
1 <= tasks.length <= 104tasks[i]是大写英文字母0 <= n <= 100
解题思路
方法一:贪心 + 构造
不妨设 是任务的个数,统计每种任务出现的次数,记录在数组 cnt 中。
假设出现次数最多的任务为 A,出现次数为 ,则至少需要 个时间单位才能安排完所有任务。如果出现次数最多的任务有 个,则需要再加上出现次数最多的任务的个数。
答案是 。
时间复杂度 。其中 是任务的种类数。
class Solution:
def leastInterval(self, tasks: List[str], n: int) -> int:
cnt = Counter(tasks)
x = max(cnt.values())
s = sum(v == x for v in cnt.values())
return max(len(tasks), (x - 1) * (n + 1) + s)
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | O(N) |
| 空间 | O(26) |
面试官常问的追问
外企场景- question_mark
They want you to stop simulating interval by interval and recognize that the most frequent task controls the schedule length.
- question_mark
They are checking whether you can turn cooldown spacing into a counting formula instead of using a heap for every interval.
- question_mark
They may ask why the answer is max(total tasks, frame formula), which tests whether you understand when idle slots disappear.
常见陷阱
外企场景- error
Using only the single maximum frequency and forgetting maxCount, which breaks cases where several task labels tie for the top count.
- error
Simulating a full schedule with sorting or a heap without noticing that LeetCode 621 has a direct counting solution.
- error
Returning the frame formula directly even when many remaining tasks fill all cooldown gaps, causing an overestimate.
进阶变体
外企场景- arrow_right_alt
Solve the same Task Scheduler input with a max heap simulation to show the schedule explicitly instead of only returning its length.
- arrow_right_alt
Change the problem so each task label has a different cooldown, which removes the simple closed-form formula.
- arrow_right_alt
Ask for the actual task order with idles included, which turns the counting shortcut into a construction problem.