LeetCode每日一题(2244. Minimum Rounds to Complete All Tasks)

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

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
    }
}

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值