LeetCode 题解工作台
完成所有任务需要的最少轮数
给你一个下标从 0 开始的整数数组 tasks ,其中 tasks[i] 表示任务的难度级别。在每一轮中,你可以完成 2 个或者 3 个 相同难度级别 的任务。 返回完成所有任务需要的 最少 轮数,如果无法完成所有任务,返回 -1 。 示例 1: 输入: tasks = [2,2,3,3,2,4,4…
4
题型
6
代码语言
3
相关题
当前训练重点
中等 · 数组·哈希·扫描
答案摘要
我们用哈希表统计每个难度级别的任务数量,然后遍历哈希表,对于每个难度级别的任务数量,如果数量为 ,则无法完成所有任务,返回 ;否则,计算完成该难度级别的任务需要的轮数,累加到答案中。 最后返回答案即可。
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 数组·哈希·扫描 题型思路
题目描述
给你一个下标从 0 开始的整数数组 tasks ,其中 tasks[i] 表示任务的难度级别。在每一轮中,你可以完成 2 个或者 3 个 相同难度级别 的任务。
返回完成所有任务需要的 最少 轮数,如果无法完成所有任务,返回 -1 。
示例 1:
输入:tasks = [2,2,3,3,2,4,4,4,4,4] 输出:4 解释:要想完成所有任务,一个可能的计划是: - 第一轮,完成难度级别为 2 的 3 个任务。 - 第二轮,完成难度级别为 3 的 2 个任务。 - 第三轮,完成难度级别为 4 的 3 个任务。 - 第四轮,完成难度级别为 4 的 2 个任务。 可以证明,无法在少于 4 轮的情况下完成所有任务,所以答案为 4 。
示例 2:
输入:tasks = [2,3,3] 输出:-1 解释:难度级别为 2 的任务只有 1 个,但每一轮执行中,只能选择完成 2 个或者 3 个相同难度级别的任务。因此,无法完成所有任务,答案为 -1 。
提示:
1 <= tasks.length <= 1051 <= tasks[i] <= 109
解题思路
方法一:哈希表
我们用哈希表统计每个难度级别的任务数量,然后遍历哈希表,对于每个难度级别的任务数量,如果数量为 ,则无法完成所有任务,返回 ;否则,计算完成该难度级别的任务需要的轮数,累加到答案中。
最后返回答案即可。
时间复杂度 ,空间复杂度 。其中 为数组 tasks 的长度。
class Solution:
def minimumRounds(self, tasks: List[int]) -> int:
cnt = Counter(tasks)
ans = 0
for v in cnt.values():
if v == 1:
return -1
ans += v // 3 + (v % 3 != 0)
return ans
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | Depends on the final approach |
| 空间 | Depends on the final approach |
面试官常问的追问
外企场景- question_mark
Evaluating the candidate's ability to use a hash table for counting frequencies and applying a greedy strategy.
- question_mark
Assessing how efficiently the candidate handles edge cases like insufficient tasks for a round.
- question_mark
Testing the candidate's ability to optimize for large input sizes by minimizing both time and space complexity.
常见陷阱
外企场景- error
Failing to handle edge cases where a task count is less than 2 for a particular difficulty level.
- error
Overcomplicating the solution by using unnecessary data structures or algorithms when a hash table and greedy approach are sufficient.
- error
Not properly optimizing the solution to handle the upper constraint of 10^5 tasks efficiently.
进阶变体
外企场景- arrow_right_alt
Allowing multiple rounds of varying task counts (2, 3, or other counts).
- arrow_right_alt
Implementing the problem with additional constraints, such as requiring a specific task order.
- arrow_right_alt
Handling more complex variations with additional task dependencies or restrictions.