- 任务调度器
给你一个用字符数组 tasks 表示的 CPU 需要执行的任务列表。其中每个字母表示一种不同种类的任务。任务可以以任意顺序执行,并且每个任务都可以在 1 个单位时间内执行完。在任何一个单位时间,CPU 可以完成一个任务,或者处于待命状态。
然而,两个 相同种类 的任务之间必须有长度为整数 n 的冷却时间,因此至少有连续 n 个单位时间内 CPU 在执行不同的任务,或者在待命状态。
你需要计算完成所有任务所需要的 最短时间 。
遇到一道之前学习算法的时候碰到的一道题,一个贪心,当时直接就学的贪心的数学,也就是桶的方法写的,这次又在leetcode上面遇到了,用模拟的方法写一下
看到一个评论用操作系统的进程轮询机制,感觉挺好的,他的实现思想是这样的:
对于一个循环至少需要n+1个时间片,也就是只要还有没有进行完的任务就需要再做一轮,最后剩余数量最大的也只剩一个结束的那轮就结束了。实现的时候,他很聪明的使用了两个队列
class Solution {
public:
int leastInterval(vector<char>& tasks, int n) {
unordered_map<char, int> mp;
for (const auto& task : tasks) {
mp[task]++;
}
priority_queue<int> pq;
for (const auto& m : mp) {
pq.push(m.second); // just care frequency, but not the task name
}
int cycle = n + 1;
int res = 0;
// Have to temporarily save the poped elements into a queue
// so that two consectutive elements wouldn't be scheduled
// together even it still has very high frequency
while (!pq.empty()) {
queue<int> q;
int count = 0;
for (int i = 0; i < cycle; i++) {
if (!pq.empty()) {
q.push(pq.top());
pq.pop();
count++;
}
}
while (!q.empty()) {
auto freq = q.front();
q.pop();
freq--;
if (freq > 0) {
pq.push(freq);
}
}
// As long as pq is not empty, we have to add n + 1 cycles to res
// it is possible that we didn't fully utilize the n + 1 cycles
// meaning there could be CPU idle time
// when pq is empty, meaning this is the last batch of tasks, we don't
// have to wait full (n + 1) cycles if count < (n +1)
res += pq.empty() ? count : cycle;
}
return res;
}
};
作者:jyj407
链接:https://leetcode-cn.com/problems/task-scheduler/solution/zhong-gui-zhong-ju-621-ren-wu-diao-du-qi-arnc/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。