621. 任务调度器 https://leetcode-cn.com/problems/task-scheduler/submissions/
给定一个用字符数组表示的 CPU 需要执行的任务列表。其中包含使用大写的 A - Z 字母表示的26 种不同种类的任务。任务可以以任意顺序执行,并且每个任务都可以在 1 个单位时间内执行完。CPU 在任何一个单位时间内都可以执行一个任务,或者在待命状态。
然而,两个相同种类的任务之间必须有长度为 n 的冷却时间,因此至少有连续 n 个单位时间内 CPU 在执行不同的任务,或者在待命状态。
你需要计算完成所有任务所需要的最短时间。
示例 1:
输入: tasks = ["A","A","A","B","B","B"], n = 2
输出: 8
执行顺序: A -> B -> (待命) -> A -> B -> (待命) -> A -> B.
注:
- 任务的总个数为 [1, 10000]。
- n 的取值范围为 [0, 100]。
思路:优先考虑数量比较多的,且可立刻执行的。
class Solution {
public:
struct node{
char c;
int times;
int intevel;
node() : times(0), intevel(-200) {};
};
node a[100];
int leastInterval(vector<char>& tasks, int n) {
int N=tasks.size();
if(N==0) return 0;
for(int i=0;i<N;i++)
{
char c=tasks[i];
a[c-'A'].times++;
}
int num=0;
for(int i=0;i<N;i++)
{
int t=getbestC(num,n);
if(t>-1)
{
a[t].times--;
a[t].intevel=num;
char tc= 'A'+t;
//cout<<tc<<"->" ;
}
else
{
i--;
//cout<<"(待命)"<<"->" ;
}
num++;
}
return num;
}
int getbestC(int num,int n)
{
int res=-1;
node indexs;
for(int i=0;i<26;i++)
{
if(a[i].times>indexs.times&&(num-a[i].intevel)>n)
{
indexs.times=a[i].times;
indexs.intevel=a[i].intevel;
res=i;
}
}
return res;
}
};