题目
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.
测试例子
Input: tasks = [‘A’,’A’,’A’,’B’,’B’,’B’], n = 2
Output: 8
Explanation: A -> B -> idle -> A -> B -> idle -> A -> B.
代码
class Solution {
public:
int leastInterval(vector<char>& tasks, int n) {
unordered_map<char,int>mp;
int count = 0;
for(auto e : tasks){
mp[e]++;
count = max(count, mp[e]);
//count 记录任务中数量最多的
}
/*因为存在最多count个的任务X,则至少需要时间片个数
(count-1)*(1+n),其他少于count的任务将会放到这些
时间片中运行。剩下就是最后一个X以及和X一样多的其他
任务的最后一个,我们只要统计剩下的个数等于count的任
务,就可以知道最后一次运行任务所需的时间片。*/
int ans = (count-1)*(n+1);
for(auto e : mp) if(e.second == count) ans++;
//考虑n=0的情况
return max((int)tasks.size(), ans);
}
};
总结
这题的切入点是相同任务之间间隔n个时间片,因此从数量最多的任务切入。不过我一开始以为存在递推关系式,后来看到大佬的短短十行代码才发现问题其实很简单。