题目描述:
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才能做同一项任务,等待时间可以做其他任务或者不工作,求一共需要多长时间才能完成所有任务。先找到出现次数最多的任务,假设次数最多的任务一共有x个,那么为了完成这些任务,就需要(max_count-1)*(n+1)+x=t,由于t的时长已经满足了次数最多的任务,所以接下来有两种情况:①t大于任务总数,说明t的时长内肯定有不工作的时间,那么其他任务必定能够安排在次数最多的任务之间。比如我们假设有一个任务A,它的次数不是最大,那么一定能在t的时长内找到一个不工作的时间用来完成这个任务,并且不会和其他的任务A冲突,因为它的次数不是最大的;②t小于等于任务总数,那么可以发现t的时长内已经保证了次数最多的任务都不会冲突,那么其他任务更加不会冲突,这时完成任务的时长就是任务的总数。因此最终结果为t和任务总数的最大值。
class Solution {
public:
int leastInterval(vector<char>& tasks, int n) {
vector<int> count(26,0);
for(int i=0;i<tasks.size();i++) count[tasks[i]-'A']++;
sort(count.begin(),count.end());
int max_count=count[25];
int x=0;
for(int i=25;i>=0;i--)
{
if(count[i]==max_count) x++;
else break;
}
return max((int)tasks.size(),(max_count-1)*(n+1)+x);
}
};