621. 任务调度器
时间:2020年12月5日
知识点:贪心、模拟
题目链接:https://leetcode-cn.com/problems/task-scheduler/
题目
给你一个用字符数组 tasks 表示的 CPU 需要执行的任务列表。其中每个字母表示一种不同种类的任务。任务可以以任意顺序执行,并且每个任务都可以在 1 个单位时间内执行完。在任何一个单位时间,CPU 可以完成一个任务,或者处于待命状态。
然而,两个 相同种类 的任务之间必须有长度为整数 n 的冷却时间,因此至少有连续 n 个单位时间内 CPU 在执行不同的任务,或者在待命状态。
你需要计算完成所有任务所需要的 最短时间 。
示例 1:
输入:tasks = [“A”,“A”,“A”,“B”,“B”,“B”], n = 2
输出:8
解释:A -> B -> (待命) -> A -> B -> (待命) -> A -> B
在本示例中,两个相同类型任务之间必须间隔长度为 n = 2 的冷却时间,而执行一个任务只需要一个单位时间,所以中间出现了(待命)状态。
示例 2:
输入:tasks = [“A”,“A”,“A”,“B”,“B”,“B”], n = 0
输出:6
解释:在这种情况下,任何大小为 6 的排列都可以满足要求,因为 n = 0
[“A”,“A”,“A”,“B”,“B”,“B”]
[“A”,“B”,“A”,“B”,“A”,“B”]
[“B”,“B”,“B”,“A”,“A”,“A”]
…
诸如此类
示例 3:
输入:tasks = [“A”,“A”,“A”,“A”,“A”,“A”,“B”,“C”,“D”,“E”,“F”,“G”], n = 2
输出:16
解释:一种可能的解决方案是:
A -> B -> C -> A -> D -> E -> A -> F -> G -> A -> (待命) -> (待命) -> A -> (待命) -> (待命) -> A
提示:
- 1 <= task.length <= 104
- tasks[i] 是大写英文字母
- n 的取值范围为 [0, 100]
解法:
-
这种题 先画图模拟一下 找找规律
-
用一个数组记录每个任务出现的次数
-
找出最大的任务量x 然后模拟 最多的任务中有x-1个空隙 每个空隙处理n个不同类型的任务
-
按照剩余任务量最多的排序 处理任务 如果没有任务了就返回
-
最后 先+1 最多任务的尾 再看看还有没有剩余的任务
-
近一步发现 我们只需要得到最多的任务量数 和 有最多任务量数的任务类型数 就可以求结
代码
#include <stdio.h>
#include <iostream>
#include <vector>
using namespace std;
/*
class Solution {
public:
int leastInterval(vector<char>& tasks, int n) {
if(n==0)
return tasks.size();
vector<int> nums(26,0);
for(char x :tasks)
nums[x-'A']++;
int maxid = 0,maxcount = 0;
for(int i = 0;i < 26;i++){
if(nums[i] > maxcount){
maxid = i;
maxcount = nums[i];
}
}
nums[maxid] = 0;
int re = tasks.size() - maxcount;
for(int i = 0; i < maxcount-1; i++){
int c = n;
sort(nums.begin(), nums.end(),greater<int>());
for(int i = 0;i < 26;i++){
if(nums[i]){
nums[i]--;
c--;
if(c == 0)
break;
}
else
break;
}
}
int x = (maxcount-1)*(n+1)+1;
for(int i=0;i<26;i++){
while(nums[i]){
nums[i]--;
x++;
}
}
return x;
}
};
*/
class Solution {
public:
int leastInterval(vector<char>& tasks, int n) {
int numsize = tasks.size();
if(n==0)
return tasks.size();
vector<int> nums(26,0);
for(char x :tasks)
nums[x-'A']++;
int maxid = 0,maxcount = 0;
for(int i = 0;i < 26;i++){
if(nums[i] > maxcount){
maxid = i;
maxcount = nums[i];
}
}
int maxnumcount = 0;
for(int i = 0;i < 26;i++){
if(nums[i] == maxcount)
maxnumcount++;
}
return max( (maxcount-1)*(n+1)+maxnumcount,numsize );
}
};
int main()
{
vector<char> task;
task.push_back('A');task.push_back('A');task.push_back('A');task.push_back('A');
task.push_back('B');task.push_back('B');task.push_back('B');task.push_back('B');
task.push_back('C');task.push_back('C');task.push_back('C');task.push_back('C');
task.push_back('D');task.push_back('D');task.push_back('D');task.push_back('D');
task.push_back('E');task.push_back('F');
int n = 4;
Solution s;
cout<<s.leastInterval(task, n)<<endl;
return 0;
}
今天也是爱zz的一天哦!