1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
class Solution {
public int minimumRounds(int[] tasks) {
Map<Integer, Integer> taskCount = new HashMap<>();
for (int task : tasks) {
taskCount.put(task, taskCount.getOrDefault(task, 0) + 1);
}
int totalRound = 0;
for (Integer count : taskCount.values()) {
if (count == 1) {
return -1;
}
if (count % 3 == 0) {
totalRound += (count / 3);
} else if (count % 3 == 1) {
totalRound += ((count / 3) + 1);
} else {
totalRound += ((count / 3) + 1);
}
}
return totalRound;
}
}

首先统计每个task的count. 如果task的个数是1, 直接返回-1; 如果除以3能整除那就是totalRound直接加上count除以3; 如果余数是1, 那么我们需要让最后四个以两轮完成也就是(count / 3) - 1 + 2. 如果余数是2, 那么还需要额外一轮于是就是(count / 3) + 1.

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