题目描述:
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 1:
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].
分析:用一个数组储存各种任务出现的次数,显然,当会出现休息周期时,所需的最少周期大于字母最大出现次数-1乘以n加一,而每有一个最大出现的字母,我们需要为周期加一,来执行他的最后一个任务。而不出现休息周期,则为任务数本身。
代码如下:
int leastInterval(vector<char>& tasks, int n) {
int element[26]={0};
int maxtotal=0;
for(int i=0;i<tasks.size();i++){
element[tasks[i]-'A']++;
maxtotal=max(maxtotal,element[tasks[i]-'A']);
}
int answer=(n+1)*(maxtotal-1);
for(int i=0;i<26;i++){
if(maxtotal==element[i])
answer++;
}
if(answer<tasks.size()) return tasks.size();
return answer;
}