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.
给定一个字符串数组tasks,里面的每个元素代表一个任务,还有一个间隔n表示CPU在执行这些任务的时候,两个相同任务之间的最小间隔,如果在某个时间片没有任务可以执行则CPU进入idle状态,直到满足了最小间隔之后再执行下一个任务。
思路一:排序
首先计算每种任务的个数,用一个map保存。然后根据个数降序排列这些任务,并从个数最多的任务开始执行。一开始的思路是遍历每种任务依次执行,后来发现这样不一定最优,然后考虑每次循环n+1次,从每种任务中依次取出一个任务执行。例如tasks = [“A”,“A”,“A”,“B”,“C”,“D”],n = 2,如果我们按照A->B->C->D->A->idle->idle->A的顺序执行,需要8步,而按照A->B->C->A->D->idle->A的顺序,只需要7步。
class Solution:
def leastInterval(self, tasks: List[str], n: int) -> int:
mapTask = [0]*26
for task in tasks:
mapTask[ord(task) - ord('A')]+=1
mapTask = sorted(mapTask)
print(mapTask)
time = 0
while (mapTask[25] > 0):
i = 0
while (i <= n):
if (mapTask[25] == 0):
break
if (i < 26 and mapTask[25 - i] > 0):
mapTask[25 - i]-=1
# 即使任务个数为0,time和i也要加1,对应了idle状态。
time+=1
i+=1
mapTask = sorted(mapTask)
return time
可以看到这里先初始化了一个mapTask数组,里面保存26个字母代表的任务个数,再升序排列一下。然后从最多的任务种类开始执行,每次循环n+1次。
THE END.