- Notifications
You must be signed in to change notification settings - Fork 1.8k
/
Copy path621_Task_Scheduler.java
45 lines (34 loc) · 1.16 KB
/
621_Task_Scheduler.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
classSolution {
publicintleastInterval(char[] tasks, intn) {
if (tasks == null || tasks.length == 0) {
return0;
}
Map<Character, Integer> hm = newHashMap<>();
PriorityQueue<Map.Entry<Character, Integer>> pq = newPriorityQueue<>(
(pair1, pair2) -> pair2.getValue() - pair1.getValue());
for (charc : tasks) {
hm.put(c, hm.getOrDefault(c, 0) + 1);
}
pq.addAll(hm.entrySet());
intcycles = 0;
while (!pq.isEmpty()) {
List<Map.Entry<Character, Integer>> temp = newArrayList<>();
intemptyTaskSlots = n + 1;
while (emptyTaskSlots > 0 && !pq.isEmpty()) {
--emptyTaskSlots;
++cycles;
Map.Entry<Character, Integer> entry = pq.poll();
entry.setValue(entry.getValue() - 1);
if (entry.getValue() > 0) {
temp.add(entry);
}
}
pq.addAll(temp);
if (pq.isEmpty()) {
break;
}
cycles += emptyTaskSlots;
}
returncycles;
}
}