目录

0621:任务调度器(★)

力扣第 621 题

题目

给你一个用字符数组 tasks 表示的 CPU 需要执行的任务列表,用字母 A 到 Z 表示,以及一个冷却时间 n。每个周期或时间间隔允许完成一项任务。任务可以按任何顺序完成,但有一个限制:两个 相同种类 的任务之间必须有长度为 n 的冷却时间。

返回完成所有任务所需要的 最短时间间隔

示例 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 <= tasks.length <= 104
  • tasks[i] 是大写英文字母
  • 0 <= n <= 100

相似问题:

分析

#1 贪心+堆

容易想到的一种方法是贪心放剩余次数最多的任务。证明见 力扣官方题解

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
class Solution:
    def leastInterval(self, tasks: List[str], n: int) -> int:
        free = sorted(-w for w in Counter(tasks).values())
        busy, t = deque(), 0
        for _ in range(len(tasks)):
            if not free:
                t = max(t,busy[0][0])
            while busy and busy[0][0]<=t:
                heappush(free,busy.popleft()[1])
            w = heappop(free)
            if -w-1>0:
                busy.append((t+n+1,w+1))
            t += 1
        return t

200 ms

#2 构造

还可以直接构造,具体见 力扣官方题解

解答

1
2
3
4
5
6
class Solution:
    def leastInterval(self, tasks: List[str], n: int) -> int:
        A = list(Counter(tasks).values())
        ma = max(A)
        w = A.count(ma)
        return max(len(tasks),(ma-1)*(n+1)+w)

64 ms