LeetCode Q 621 - Task Scheduler
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: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].
Solution
Solution 1: Filling Solts
- count the number of each task
- sort tasks according to their count number
- find number of tasks who has the maximum task numbers
- fill the solts
Code:
public int leastInterval(char[] tasks, int n) {
int[] count = new int[26];
for (char task: tasks)
count[task- 'A']++;
Arrays.sort(count);
int firstMaxTasksIndex = 25;
while (firstMaxTasksIndex >= 0 && count[25] == count[firstMaxTasksIndex])
firstMaxTasksIndex--;
return Math.max(tasks.length, (count[25] - 1) * (n + 1) + (25 - firstMaxTasksIndex));
}
Solution 2: PriorityQueue
Code:
public int leastInterval(char[] tasks, int n) {
int[] count = new int[26];
for (char task: tasks)
count[task- 'A']++;
// int[index, value]
PriorityQueue<int[]> pq= new PriorityQueue<>( (a, b) -> {
if (a[1] != b[1])
return b[1] - a[1];
return a[0] - b[0];
});
for (int i = 0; i < 26; i++) {
if (count[i] > 0)
pq.offer(new int[]{i, count[i]});
}
int res = 0;
while (!pq.isEmpty()) {
List<int[]> temp = new ArrayList<>();
int k = n + 1;
while (k > 0 && !pq.isEmpty()) {
int[] curr = pq.poll();
curr[1]--; temp.add(curr);
k--; res++;
}
for (int[] arr: temp) {
if (arr[1] > 0)
pq.offer(arr);
}
if (pq.isEmpty()) break;
res += k;
}
return res;
}