题干
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].
思路
重点,任务可以以任何顺序执行,并不是FIFO。所以频率最高的任务之间间隔n的排列方式是最短的
当然要考虑频率最高的不止一个任务
ret = max(len(tasks),(n+1) * maxnum + 1 + maxcount - 1)
代码
class Solution(object):
def leastInterval(self, tasks, n):
"""
:type tasks: List[str]
:type n: int
:rtype: int
"""
a = []
for i in range(0, 26):
a.append(0)
for i in range(0, len(tasks)):
index = ord(tasks[i]) - ord('A')
a[index] = a[index] + 1
a.sort()
i = 25
while i > 0 and a[i] == a[-1]:
i = i - 1
ret = max(len(tasks), (n+1) * (a[-1]-1) + 25 - i)
return ret