[leetcode]Task Scheduler
链接:https://leetcode.com/problems/task-scheduler/description/
Question
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
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].
Solution
class Solution {
public:
// 这道题真的是靠智商。。
// 步骤如下:以 AACCCDDEEE 3 为例子
// 1、对于一个字符串,找到频率最大的一部分字符,如CE
// 2、以CE为分隔符,3为分隔间距划分如CEXXCEXXCE[长度是(3-1)*(4)+2]
// 3、将剩下的字符填入中间的空位(尽量填的均匀--也就是空的区间大小差不多,不会出现3和1,而是2和2)
// 4、对于3,如果剩下的字符个数 <= 中间的空位,可以直接填满,此时长度是(3-1)*(4)+2。
// 如果剩余的字符 > 中间的空位,填不满,但是实际上可以填在每个分割区间的最后面,长度是字符串长度。
// 5、由于此题只需要求长度,因此直接找4中的较大值就可以了
int leastInterval(vector<char>& tasks, int n) {
vector<int> vec;
vec.resize(26, 0);
for (int i = 0; i < tasks.size(); i++) vec[tasks[i]-'A']++;
sort(vec.begin(), vec.end());
int cnt = 0;
int max_val = vec[vec.size()-1];
for (int i = vec.size()-1; i >= 0; i--)
if (vec[i] == max_val)
cnt++;
return max((int)tasks.size(), (max_val-1)*(n+1)+cnt);
}
};
思路:贪心算法,具体看注释。