title
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.
solution
直译本题就是任务规划,题目的核心意思是,安排一堆任务,这些任务由一个task数组给出,相同任务之间,最少有n的运行时间间隔,在n的运行时间间隔内,可以执行执行别的任务或者处于就绪状态。最终的目标是安排所有的task,使总的运行时间最小。
求最长长度,分配打散即可
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]);
}
int ans = (count - 1)*(n + 1);
for (auto e : mp) if (e.second == count) ans++; //最后A->B这俩小尾巴
return max((int)tasks.size(), ans);
}