Leetcode 621 Task Scheduler
Approach #1 Using Sorting [Accepted]
But, there is a flaw in the above idea. Consider the case, where say the number of instances of tasks A, B, C, D, E are 6, 1, 1, 1, 1 respectively with n=2(cooling time). If we go by the above method, firstly we give 1 round to each A, B, C, D and E. Now, only 5 instances of A are pending, but each instance will take 3 time units to complete because of cooling time. But a better way to schedule the tasks will be this: A, B, C, A, D, E, … . In this way, by giving turn to the task A as soon as its cooling time is over, we can save a good number of clock cycles.
Note:
It contains capital letters A to Z where different letters represent different tasks.
int[] map = new int[26];
for (char c: tasks)
map[c - 'A']++;
Arrays.sort(map);
Approach #2 Using Priority-Queue [Accepted]
int[] map = new int[26];
for (char c: tasks)
map[c - 'A']++;
PriorityQueue < Integer > queue = new PriorityQueue < >(26,Collections.reverseOrder());
for (int f: map) {
if (f > 0)
queue.add(f);
}
Approach #3 Calculating Idle slots [Accepted]
We can observe that the maximum number of idle slots will always be given by the product of the cooling time and the number of instances of the task with maximum count less 1.
For example 1:
Input: tasks = [“A”,“A”,“A”,“B”,“B”,“B”,“C”, “C”, " D"], n = 2
Output: 9
[A, B, C]
[A, B, C]
[A, B]
[D, idle]
return tasks.length
Input: tasks = [“A”,“A”,“A”,“B”,“B”], n = 2
Output: 7
[A, B, idle]
[A, B, idle]
[A, idle, idle]
public class Solution {
public int leastInterval(char[] tasks, int n) {
int[] map = new int[26];
for (char c: tasks)
map[c - 'A']++;
Arrays.sort(map);
int max_val = map[25] - 1, idle_slots = max_val * n;
for (int i = 24; i >= 0 && map[i] > 0; i--) {
idle_slots -= Math.min(map[i], max_val);
}
return idle_slots > 0 ? idle_slots + tasks.length : tasks.length;
}
}
本文深入解析了LeetCode上的621题——任务调度器,探讨了三种解决方案:排序法、优先队列法及计算空闲槽法。通过具体案例,展示了如何优化任务调度,减少等待时间,提高效率。
885

被折叠的 条评论
为什么被折叠?



