您的位置:首页 > 其它

LeetCode打卡:621. 任务调度器

2020-07-18 17:31 113 查看

给定一个用字符数组表示的 CPU 需要执行的任务列表。其中包含使用大写的 A - Z 字母表示的26 种不同种类的任务。任务可以以任意顺序执行,并且每个任务都可以在 1 个单位时间内执行完。CPU 在任何一个单位时间内都可以执行一个任务,或者在待命状态。

然而,两个相同种类的任务之间必须有长度为 n 的冷却时间,因此至少有连续 n 个单位时间内 CPU 在执行不同的任务,或者在待命状态。

你需要计算完成所有任务所需要的最短时间。

示例 :

输入:tasks = [“A”,“A”,“A”,“B”,“B”,“B”], n = 2
输出:8
解释:A -> B -> (待命) -> A -> B -> (待命) -> A -> B.
在本示例中,两个相同类型任务之间必须间隔长度为 n = 2 的冷却时间,而执行一个任务只需要一个单位时间,所以中间出现了(待命)状态。

链接:https://leetcode.com/problems/task-scheduler/

解题思路:
法一:排序思想,每n+1次为一轮,降序遍历排序数组。

class Solution(object):
def leastInterval(self, tasks, n):
"""
:type tasks: List[str]
:type n: int
:rtype: int
"""
l = len(tasks)
if l <= 1:
return l
arr = [0] * 26
for t in tasks:
arr[ord(t) - ord('A')] += 1
arr.sort()
res = 0

# 次数最高为1时跳出循环
while arr[-1] != 1:
i = 1
while i <= n + 1:   # 每n + 1个时间单位为1轮
res += 1
if i <= 26 and arr[-i] :
arr[-i] -= 1
i += 1
arr.sort()          # 每轮完成后重新排序
for i in range(25, -1, -1):
if arr[i] == 1:
res += 1
else:
return res

法二:桶思想

class Solution(object):
def leastInterval(self, tasks, n):
"""
:type tasks: List[str]
:type n: int
:rtype: int
"""
# 桶思想
l = len(tasks)
if l <= 1:
return l
h = {}
max_ = 0
first_max_cnt = 0
# 找出最大次数
for t in tasks:
if t not in h:
h[t] = 1
else:
h[t] += 1
max_ = max(max_, h[t])
# 找出有多少个并列最多的任务,即最后一个桶的任务
for key in h:
if h[key] == max_:
first_max_cnt += 1

return max((max_ - 1)*(n + 1) + first_max_cnt, l)
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: