算法的重要性,我就不多说了吧,想去大厂,就必须要经过基础知识和业务逻辑面试+算法面试。所以,为了提高大家的算法能力,这个公众号后续每天带大家做一道算法题,题目就从LeetCode上面选 !
今天和大家聊的问题叫做 任务调度器,我们先来看题面:
https://leetcode.cn/problems/task-scheduler/
Given a characters array tasks, representing the tasks a CPU needs to do, where each letter represents a different task. Tasks could be done in any order. Each task is done in one unit of time. For each unit of time, the CPU could complete either one task or just be idle.
However, there is a non-negative integer n that represents the cooldown period between two same tasks (the same letter in the array), that is that there must be at least n units of time between any two same tasks.
Return the least number of units of times that the CPU will take to finish all the given tasks.
给你一个用字符数组 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
解题
https://blog.csdn.net/cx_cs/article/details/123708803
思路:最多的那个任务设x个,间隔n,开x个桶,每个桶容量x+1,桶用来填充其他任务即每个桶有1+其他x个。
1、前x-1桶都会执行n次就算填不满,最后一桶执行完了就没了,即(x-1)(n+1)+最后一桶数量cnt,根据贪心,最后一桶只放那些数量等于x的,其他都放前x-1桶哪怕装不下
2、桶装不下可以继续填桶后,仍然是一桶一桶来执行
3、只有两种极端情况
3.1数量为x的超过n+1个,这样我们挂桶后,其实不存在空闲时间,最大是task.size()
3.2桶没装满,(x-1)(n+1)+最后一桶数量cnt
class Solution {
public:
int leastInterval(vector<char>& tasks, int n) {
int len=tasks.size();
vector<int> vec(26);
for(char c:tasks) ++vec[c-'A'];
sort(vec.begin(),vec.end(),[](int& x,int&y){return x>y;});
int cnt=1;//1开始是第二多的
while(cnt<vec.size()&&vec[cnt]==vec[0]) cnt++;
return max(len,cnt+(n+1)*(vec[0]-1) );
}
};
上期推文: