Task Scheduler
题目来源:https://leetcode.com/problemset/algorithms/
题目类型:贪心算法
-题目描述-
-实现思路-
-代码实现-
题目描述
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.
实现思路
题意为将一组任务全部做完。每个时间片只能完成一个任务或者空闲。两个相同的任务之间相差的时间片的数目不能小于n。
我们可以将n+1个时间片作为一个分组。这个分组中要填充各不相同的任务或空闲。最终分组的数目为s,最后一个分组任务的数目为k,最终花费的时间片的数目为(s-1)*(n+1)+k;
(1)计算一组任务中相同的任务的数目并放入priority_queue中。
(2)每个n+1大小的分组从priority_queue中拿出前n+1个元素,并将这前n+1个元素的值-1,将这n+1个元素中值非零的重新放回priority_queue;
如果priority_queue的元素数目小于n+1则剩下的时间片将空闲。
(3)重复步骤(2)直到priority_queue为空。
代码实现
@requires_authorization
class Solution {
public:
int leastInterval(vector<char>& tasks, int n) {
map<char, int> mymap;
for (int i = 0; i <tasks.size(); i++) {
mymap[tasks[i]]++;
}
priority_queue<int> q;
for (map<char, int>::iterator it = mymap.begin(); it != mymap.end(); it++) {
q.push(it->second);
}
int result = 0;
int t = 0;
priority_queue<int> q1;
while (!q.empty()) {
t = 0;
for (int i = 0; i < n+1; i++) {
if (q.empty()) break;
int temp = q.top();
temp--;
if (temp > 0)
q1.push(temp);
q.pop();
t++;
}
while (!q1.empty()) {
int temp = q1.top();
q.push(temp);
q1.pop();
}
result++;
}
return (result - 1)*(n+1)+t;
}
};