LeetCode 621. Task Scheduler
考点 | 难度 |
---|---|
Greedy | Easy |
题目
You have an array of CPU tasks named from A to Z and cooling time n. On each cycle/interval you can complete one task. The tasks can done in any order. The only constraint is that repeated tasks should be at least n intervals appart from each other because of the cooling time.
Return the least number of intervals needed to process all the tasks.
思路
用dictionary保存task和出现的次数,max_occ为最高的次数。建max_occ-1个组,每个组n + 1个task,填不一样的task和一个idle。最后把剩下的出现次数最多的task填完。
答案
from collections import Counter
class Solution:
def leastInterval(self, tasks, n):
if n == 0:
return len(tasks)
task_occ_dict = Counter( tasks )
max_occ = max( task_occ_dict.values() )
number_of_taks_of_max_occ = sum( ( 1 for task, occ in task_occ_dict.items() if occ == max_occ ) )
intervl_for_schedule = ( max_occ-1 )*( n+1 ) + number_of_taks_of_max_occ
return max( len(tasks), intervl_for_schedule)