一、题目
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 = 0if 1 in cnt.values():return -1return 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;}
};