题目描述
给你一个用字符数组 tasks
表示的 CPU 需要执行的任务列表,用字母 A 到 Z 表示,以及一个冷却时间 n
。每个周期或时间间隔允许完成一项任务。任务可以按任何顺序完成,但有一个限制:两个 相同种类 的任务之间必须有长度为 n
的冷却时间。
返回完成所有任务所需要的 最短时间间隔 。
示例 1:
输入:tasks = ["A","A","A","B","B","B"], n = 2
输出:8
解释:
在完成任务 A 之后,你必须等待两个间隔。对任务 B 来说也是一样。在第 3 个间隔,A 和 B 都不能完成,所以你需要待命。在第 4 个间隔,由于已经经过了 2 个间隔,你可以再次执行 A 任务。
示例 2:
输入:tasks = ["A","C","A","B","D","B"], n = 1
输出:6
解释:一种可能的序列是:A -> B -> C -> D -> A -> B。
由于冷却间隔为 1,你可以在完成另一个任务后重复执行这个任务。
示例 3:
输入:tasks = ["A","A","A","B","B","B"], n = 3
输出:10
解释:一种可能的序列为:A -> B -> idle -> idle -> A -> B -> idle -> idle -> A -> B。
只有两种任务类型,A 和 B,需要被 3 个间隔分割。这导致重复执行这些任务的间隔当中有两次待命状态。
思路
贪心法,视频参考:leetcode-贪心算法篇 621题 任务调度器_哔哩哔哩_bilibili,会让你看懂(max_count-1)*(n+1)是怎么来的;代码参考:. - 力扣(LeetCode)也可以看我写的代码
1)统计每个task出现的次数
2)找到出现次数最多的task
3)利用公式先计算出一个初步的res
4)在遍历字典,找到最多次数一共有几个task,进行追加
from collections import defaultdict
class Solution(object):
def leastInterval(self, tasks, n):
"""
:type tasks: List[str]
:type n: int
:rtype: int
"""
length = len(tasks)
if length<=1:
return length
taks_dict = defaultdict(int)
for i in tasks:
taks_dict[i]+=1
sort_tasks = sorted(taks_dict.items(), key=lambda x: x[1], reverse=True)
max_count = sort_tasks[0][1]
res = (max_count-1) * (n+1)
for i in sort_tasks:
if i[1]==max_count:
res+=1
return res if res>=length else length
if __name__=='__main__':
s = Solution()
tasks = ["A", "A", "A", "B", "B", "B"]
n = 2
print(s.leastInterval(tasks, n))
二刷:
class Solution(object):
def leastInterval(self, tasks, n):
"""
:type tasks: List[str]
:type n: int
:rtype: int
"""
count_dict = {}
for task in tasks:
if task not in count_dict:
count_dict[task] = 1
else:
count_dict[task] += 1
sort_task = sorted(count_dict.items(),key=lambda x: x[1], reverse=True)
max_count = sort_task[0][1]
res = (max_count-1) * (n+1)
for k,v in count_dict.items():
if v==max_count:
res+=1
return res if res>len(tasks) else len(tasks)
记忆点:
贪心算法,先算最多出现任务需要的数:(max_count-1) * (n+1),之后有相同的就累加;最后算出来的如果小于原本任务的长度则返沪原本的数组长度