forked from gouthampradhan/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathTaskScheduler.java
93 lines (82 loc) · 2.65 KB
/
TaskScheduler.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
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
package greedy;
import java.util.*;
/**
* Created by gouthamvidyapradhan on 26/11/2017.
*
* Given a char array representing tasks CPU need to do. It contains capital letters A to Z where different letters represent different tasks.Tasks could be done without original order. Each task could be done in one interval. For each interval, CPU could finish one task or just be idle.
However, there is a non-negative cooling interval n that means between two same tasks, there must be at least n intervals that CPU are doing different tasks or just be idle.
You need to return the least number of intervals the CPU will take to finish all the given tasks.
Example 1:
Input: tasks = ["A","A","A","B","B","B"], n = 2
Output: 8
Explanation: A -> B -> idle -> A -> B -> idle -> A -> B.
Note:
The number of tasks is in the range [1, 10000].
The integer n is in the range [0, 100].
*/
public class TaskScheduler {
class Task {
char t;
int count;
Task(char t, int count){
this.t = t;
this.count = count;
}
public int getCount() {
return count;
}
public void setCount(int count) {
this.count = count;
}
}
/**
* Main method
* @param args
*/
public static void main(String[] args) {
char[] tasks = {'A','A','A','B','B','B'};
System.out.println(new TaskScheduler().leastInterval(tasks, 2));
}
/**
*
* @param tasks
* @param n
* @return
*/
public int leastInterval(char[] tasks, int n) {
PriorityQueue<Task> queue = new PriorityQueue<>(Comparator.comparing(Task::getCount).reversed());
List<Task> waiting = new ArrayList<>();
Map<Character, Integer> map = new HashMap<>();
for(char c : tasks){
if(map.get(c) == null){
map.put(c, 1);
} else{
int v = map.get(c) + 1;
map.put(c, v);
}
}
for(char c : map.keySet()){
Task task = new Task(c, map.get(c));
queue.offer(task);
}
int count = 0;
while(!queue.isEmpty()){
int i = 0;
while(i <= n){
if(!queue.isEmpty()){
Task task = queue.poll();
task.count--;
if(task.count > 0){
waiting.add(task);
}
}
count++;
if(queue.isEmpty() && waiting.isEmpty()) break;
i++;
}
queue.addAll(waiting);
waiting.clear();
}
return count;
}
}