贪心+数学

一、题目

1、题目描述

给你一个下标从 0 开始的整数数组 tasks ,其中 tasks[i] 表示任务的难度级别。在每一轮中,你可以完成 2 个或者 3 个 相同难度级别 的任务。

返回完成所有任务需要的 最少 轮数,如果无法完成所有任务,返回 -1 

2、接口描述

python3
class Solution:
    def minimumRounds(self, tasks: List[int]) -> int:
cpp
class Solution {
public:
    int minimumRounds(vector<int>& tasks) {
        
    }
};

3、原题链接

2244. 完成所有任务需要的最少轮数


二、解题报告

1、思路分析

一次遍历记录元素出现次数

如果有某个元素次数为1,那么返回-1

否则剩下的我们优先拿3,那么最终余数可能为0、1、2

余数为1,我们需要把一次拿3操作换为两次拿2操作

余数为2,我们需要进行一次拿2操作

那么对于次数c,我们的操作次数就是(c + 2) / 3

2、复杂度

时间复杂度: O(n)空间复杂度:O(n)

3、代码详解

python3
class Solution:
    def minimumRounds(self, tasks: List[int]) -> int:
        cnt = Counter(tasks)
        ret = 0
        if 1 in cnt.values():
            return -1
        return sum((c + 2) // 3 for c in cnt.values())
cpp
class Solution {
public:
    int minimumRounds(vector<int>& tasks) {
        unordered_map<int, int> cnt;
        for(int x : tasks) cnt[x] ++;
        int ret = 0;
        for (auto& p : cnt) {
            if (p.second == 1) return -1;
            ret += (p.second + 2) / 3;
        }
        return ret;
    }
};

  • 8
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

EQUINOX1

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值