Given a char array representing tasks CPU need to do. It contains capital letters A to Z where different letters represent different tasks. Tasks could be done without original order. Each task could be done in one interval. For each interval, CPU could finish one task or just be idle.
However, there is a non-negative cooling interval n that means between two same tasks, there must be at least n intervals that CPU are doing different tasks or just be idle.
You need to return the least number of intervals the CPU will take to finish all the given tasks.
Example:
Input: tasks = ["A","A","A","B","B","B"], n = 2
Output: 8
Explanation: A -> B -> idle -> A -> B -> idle -> A -> B.
Note:
- The number of tasks is in the range [1, 10000].
- The integer n is in the range [0, 100].
LeetCode:链接
给定一串任务数组,任务用字符A-Z表示,每个字符代表一个任务。给定数字n,要求两个相同任务之间间隔至少为n,间隔期间可以安排别的任务或者等待,求出完成数组中的任务所需的最小时间间隔。(一个任务需要一个时间间隔)
如给定:AAABBCD,n=2。那么我们满足个数最多的任务所需的数量,即可以满足任务间隔要求,即:AXXAXXA;(其中,X表示需要填充任务或者idle的间隔).
如果有两种或两种以上的任务具有相同的最多的任务数,如:AAAABBBBCCDE,n=3。那么我们将具有相同个数的任务A和B视为一个任务对,最终满足要求的分配为:ABXXABXXABXXAB,剩余的任务在不违背要求间隔的情况下穿插进间隔位置即可,空缺位置补idle。
由上面的分析我们可以得到最终需要最少的任务时间:(最多任务数-1)*(n + 1) + (相同最多任务的任务个数)。
不要忘记对任务数求最大值,毕竟每个任务都是要调度一遍的。比如对于测试用例["A","A","A","B","B","B"],0
,公式求得是(3-1)*(0+1)+2=4,而事实上,任务最少都要被调度一遍的,所以必须对任务个数求个最大值。
class Solution(object):
def leastInterval(self, tasks, n):
"""
:type tasks: List[str]
:type n: int
:rtype: int
"""
countDict = {}
for task in tasks:
countDict[task] = countDict.get(task, 0) + 1
maxCount = max(countDict.values())
maxMost = 0
for each in countDict:
if countDict[each] == maxCount:
maxMost += 1
maxtime = (maxCount - 1) * (n + 1) + maxMost
return max(len(tasks), maxtime)