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)
相关文章推荐
- leetcode 621. Task Scheduler CPU任务调度 + 数学公式
- leetcode621任务调度器
- spring任务调度器quartz 时间配置
- 任务调度器quatrz.触发机制表达式Cron
- python获取微信企业号打卡数据并生成windows计划任务
- leetcode 打卡 2018.03.06 #766 Toepliz Matrix
- L621. 任务调度器
- 2018.03.07 leetcode 打卡 #169. Majority Element
- Gearman一个异步任务调度器
- Datawhale 组队学习打卡营 任务21:图像分类案例1
- Datawhale 组队学习打卡营 任务5:语言模型
- 2018.03.09 leetcode 打卡 #pivotIndex
- 2018.3.12 leetcode打卡 #66 plus one
- LeetCode高频面试60天打卡日记Day06
- 2018.03.14 leetcode 打卡 # 118 pascal triangel
- leetcode打卡07——合并两个有序链表
- 2018.03.15 leetcode 打卡 #268. Missing Number
- Quartz任务调度器的使用
- 2018.03.22 leetcode 打卡
- MapReduce多用户任务调度器——容量调度器(Capacity Scheduler)原理和源码研究