给定一个用字符数组表示的 CPU 需要执行的任务列表。其中包含使用大写的 A - Z 字母表示的26 种不同种类的任务。任务可以以任意顺序执行,并且每个任务都可以在 1 个单位时间内执行完。CPU 在任何一个单位时间内都可以执行一个任务,或者在待命状态。
然而,两个相同种类的任务之间必须有长度为 n 的冷却时间,因此至少有连续 n 个单位时间内 CPU 在执行不同的任务,或者在待命状态。
你需要计算完成所有任务所需要的最短时间。
示例 :
输入:tasks = ["A","A","A","B","B","B"], n = 2
输出:8
解释:A -> B -> (待命) -> A -> B -> (待命) -> A -> B.
在本示例中,两个相同类型任务之间必须间隔长度为 n = 2 的冷却时间,而执行一个任务只需要一个单位时间,所以中间出现了(待命)状态。
class Solution { public int leastInterval(char[] tasks, int n) { int[] count = new int[26]; for(char ch : tasks) { count[ch - ‘A‘]++; } Arrays.sort(count); int maxCount = 0; //统计有多少个频率最高的字母 for (int i = 25; i >= 0; i--) { if(count[i] != count[25]){ break; } maxCount++; } //公式算出的值可能会比数组的长度小,取两者中最大的那个 return Math.max((count[25] - 1) * (n + 1) + maxCount , tasks.length); } } public class Solution { public int leastInterval(char[] tasks, int n) { 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); } int time = 0; while (!queue.isEmpty()) { int i = 0; List < Integer > temp = new ArrayList < > (); // 循环 n + 1次,为一次完整的任务切换调度等待时间 while (i <= n) { if (!queue.isEmpty()) { if (queue.peek() > 1) temp.add(queue.poll() - 1); else queue.poll(); } time++; if (queue.isEmpty() && temp.size() == 0) break; i++; } for (int l: temp) queue.add(l); } return time; } }
提示:
任务的总个数为 [1, 10000]。
n 的取值范围为 [0, 100]。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/task-scheduler
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
原文:https://www.cnblogs.com/PHUN19/p/13395157.html