一、題目
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;}
};