44
44
45
45
<!-- 这里可写通用的实现逻辑 -->
46
46
47
+ ** 方法一:哈希表**
48
+
49
+ 我们用哈希表统计每个难度级别的任务数量,然后遍历哈希表,对于每个难度级别的任务数量,如果数量为 $1$,则无法完成所有任务,返回 $-1$;否则,计算完成该难度级别的任务需要的轮数,累加到答案中。
50
+
51
+ 最后返回答案即可。
52
+
53
+ 时间复杂度 $O(n)$,空间复杂度 $O(n)$。其中 $n$ 为数组 ` tasks ` 的长度。
54
+
47
55
<!-- tabs:start -->
48
56
49
57
### ** Python3**
54
62
class Solution :
55
63
def minimumRounds (self , tasks : List[int ]) -> int :
56
64
cnt = Counter(tasks)
57
- mi = min (cnt.values())
58
- if mi == 1 :
59
- return - 1
60
- return sum (v // 3 + (0 if v % 3 == 0 else 1 ) for v in cnt.values())
65
+ ans = 0
66
+ for v in cnt.values():
67
+ if v == 1 :
68
+ return - 1
69
+ ans += v // 3 + (v % 3 != 0 )
70
+ return ans
61
71
```
62
72
63
73
### ** Java**
@@ -69,7 +79,7 @@ class Solution {
69
79
public int minimumRounds (int [] tasks ) {
70
80
Map<Integer , Integer > cnt = new HashMap<> ();
71
81
for (int t : tasks) {
72
- cnt. put (t, cnt . getOrDefault(t, 0 ) + 1 );
82
+ cnt. merge (t, 1 , Integer :: sum );
73
83
}
74
84
int ans = 0 ;
75
85
for (int v : cnt. values()) {
@@ -83,37 +93,22 @@ class Solution {
83
93
}
84
94
```
85
95
86
- ### ** TypeScript**
87
-
88
- ``` ts
89
- function minimumRounds(tasks : number []): number {
90
- let hashMap = new Map ();
91
- for (let key of tasks ) {
92
- hashMap .set (key , (hashMap .get (key ) || 0 ) + 1 );
93
- }
94
- let ans = 0 ;
95
- for (let key of hashMap .keys ()) {
96
- let val = hashMap .get (key );
97
- if (val < 2 ) return - 1 ;
98
- const ctn = Math .floor (val / 3 ) + (val % 3 == 0 ? 0 : 1 );
99
- ans += ctn ;
100
- }
101
- return ans ;
102
- }
103
- ```
104
-
105
96
### ** C++**
106
97
107
98
``` cpp
108
99
class Solution {
109
100
public:
110
101
int minimumRounds(vector<int >& tasks) {
111
102
unordered_map<int, int> cnt;
112
- for (int& t : tasks) ++cnt[ t] ;
103
+ for (auto& t : tasks) {
104
+ ++cnt[ t] ;
105
+ }
113
106
int ans = 0;
114
107
for (auto& [ _ , v] : cnt) {
115
- if (v == 1) return -1;
116
- ans += v / 3 + (v % 3 == 0 ? 0 : 1);
108
+ if (v == 1) {
109
+ return -1;
110
+ }
111
+ ans += v / 3 + (v % 3 != 0);
117
112
}
118
113
return ans;
119
114
}
@@ -142,6 +137,25 @@ func minimumRounds(tasks []int) int {
142
137
}
143
138
```
144
139
140
+ ### ** TypeScript**
141
+
142
+ ``` ts
143
+ function minimumRounds(tasks : number []): number {
144
+ const cnt = new Map ();
145
+ for (const t of tasks ) {
146
+ cnt .set (t , (cnt .get (t ) || 0 ) + 1 );
147
+ }
148
+ let ans = 0 ;
149
+ for (const v of cnt .values ()) {
150
+ if (v == 1 ) {
151
+ return - 1 ;
152
+ }
153
+ ans += Math .floor (v / 3 ) + (v % 3 === 0 ? 0 : 1 );
154
+ }
155
+ return ans ;
156
+ }
157
+ ```
158
+
145
159
### ** ...**
146
160
147
161
```
0 commit comments