You are given a 0-indexed integer array tasks, where tasks[i] represents the difficulty level of a task. In each round, you can complete either 2 or 3 tasks of the same difficulty level.
Return the minimum rounds required to complete all the tasks, or -1 if it is not possible to complete all the tasks.
Example 1:
Input: tasks = [2,2,3,3,2,4,4,4,4,4]
Output: 4
Explanation: To complete all the tasks, a possible plan is:
- In the first round, you complete 3 tasks of difficulty level 2.
- In the second round, you complete 2 tasks of difficulty level 3.
- In the third round, you complete 3 tasks of difficulty level 4.
- In the fourth round, you complete 2 tasks of difficulty level 4.
It can be shown that all the tasks cannot be completed in fewer than 4 rounds, so the answer is 4.
Example 2:
Input: tasks = [2,3,3]
Output: -1
Explanation: There is only 1 task of difficulty level 2, but in each round, you can only complete either 2 or 3 tasks of the same difficulty level. Hence, you cannot complete all the tasks, and the answer is -1.
Constraints:
- 1 <= tasks.length <= 105
- 1 <= tasks[i] <= 109
对于难度 d, 如果:
- task 数量为 1, 因为我们只能同时处理 2 或者 3 个 task, 所以该 task 我们无法完成, 返回-1
- task 数量为 2, 1 次即可完成
- task 数量为 3, 1 次即可完成
- task 数量>=4, 为了使次数最少, 我们应该优先同时处理 3 个 task,但是如果 num % 3 == 1, 那就意味着剩余的那 1 个 task 我们无法处理, 我们把这种情况罗列一下, 4, 7, 10, 13…, 我们可以发现这些数字都可以拆解成 4 + n * 3 的形式, 4 我们可以用 2 步处理完, 所以处理这些数字的步数就是(x - 4) / 3 + 2
use std::collections::HashMap;
impl Solution {
pub fn minimum_rounds(tasks: Vec<i32>) -> i32 {
let m = tasks.into_iter().fold(HashMap::new(), |mut m, t| {
*m.entry(t).or_insert(0) += 1;
m
});
let mut counts: Vec<i32> = m.values().map(|&v| v).collect();
counts.sort();
let mut ans = 0;
for c in counts {
match c {
1 => return -1,
2 => ans += 1,
3 => ans += 1,
_ => {
ans += (c - 4) / 3 + 2;
}
}
}
ans
}
}

给定一个表示任务难度的整数数组,每轮可以完成相同难度的2或3个任务。返回完成所有任务所需的最少回合数,如果无法完成则返回-1。优先处理3个任务的情况以减少回合数,例如,若任务数量为4n+1,则需要(n+1)回合加上额外的2回合。
1803

被折叠的 条评论
为什么被折叠?



