comments | difficulty | edit_url | tags | ||||||
---|---|---|---|---|---|---|---|---|---|
true |
中等 |
|
给你一个用字符数组 tasks
表示的 CPU 需要执行的任务列表,用字母 A 到 Z 表示,以及一个冷却时间 n
。每个周期或时间间隔允许完成一项任务。任务可以按任何顺序完成,但有一个限制:两个 相同种类 的任务之间必须有长度为 n
的冷却时间。
返回完成所有任务所需要的 最短时间间隔 。
示例 1:
输入:tasks = ["A","A","A","B","B","B"], n = 2 输出:8 解释:A -> B -> (待命) -> A -> B -> (待命) -> A -> B 在本示例中,两个相同类型任务之间必须间隔长度为 n = 2 的冷却时间,而执行一个任务只需要一个单位时间,所以中间出现了(待命)状态。
示例 2:
输入:tasks = ["A","A","A","B","B","B"], n = 0 输出:6 解释:在这种情况下,任何大小为 6 的排列都可以满足要求,因为 n = 0 ["A","A","A","B","B","B"] ["A","B","A","B","A","B"] ["B","B","B","A","A","A"] ... 诸如此类
示例 3:
输入:tasks = ["A","A","A","A","A","A","B","C","D","E","F","G"], n = 2 输出:16 解释:一种可能的解决方案是: A -> B -> C -> A -> D -> E -> A -> F -> G -> A -> (待命) -> (待命) -> A -> (待命) -> (待命) -> A
提示:
1 <= tasks.length <= 104
tasks[i]
是大写英文字母0 <= n <= 100
不妨设 cnt
中。
假设出现次数最多的任务为 A
,出现次数为
答案是
时间复杂度
class Solution:
def leastInterval(self, tasks: List[str], n: int) -> int:
cnt = Counter(tasks)
x = max(cnt.values())
s = sum(v == x for v in cnt.values())
return max(len(tasks), (x - 1) * (n + 1) + s)
class Solution {
public int leastInterval(char[] tasks, int n) {
int[] cnt = new int[26];
int x = 0;
for (char c : tasks) {
c -= 'A';
++cnt[c];
x = Math.max(x, cnt[c]);
}
int s = 0;
for (int v : cnt) {
if (v == x) {
++s;
}
}
return Math.max(tasks.length, (x - 1) * (n + 1) + s);
}
}
class Solution {
public:
int leastInterval(vector<char>& tasks, int n) {
vector<int> cnt(26);
int x = 0;
for (char c : tasks) {
c -= 'A';
++cnt[c];
x = max(x, cnt[c]);
}
int s = 0;
for (int v : cnt) {
s += v == x;
}
return max((int) tasks.size(), (x - 1) * (n + 1) + s);
}
};
func leastInterval(tasks []byte, n int) int {
cnt := make([]int, 26)
x := 0
for _, c := range tasks {
c -= 'A'
cnt[c]++
x = max(x, cnt[c])
}
s := 0
for _, v := range cnt {
if v == x {
s++
}
}
return max(len(tasks), (x-1)*(n+1)+s)
}
public class Solution {
public int LeastInterval(char[] tasks, int n) {
int[] cnt = new int[26];
int x = 0;
foreach (char c in tasks) {
cnt[c - 'A']++;
x = Math.Max(x, cnt[c - 'A']);
}
int s = 0;
foreach (int v in cnt) {
s = v == x ? s + 1 : s;
}
return Math.Max(tasks.Length, (x - 1) * (n + 1) + s);
}
}