LeetCode--621. Task Scheduler(任务安排)Python

题目:

给定一串任务数组,任务用字符A-Z表示,每个字符代表一个任务。给定数字n,要求两个相同任务之间间隔至少为n,间隔期间可以安排别的任务或者等待,求出完成数组中的任务所需的最小时间间隔。(一个任务需要一个时间间隔)

解题思路:

先统计数组中各个任务出现的次数。优先安排次数最多的任务。次数最多的任务安排完成之后所需的时间间隔为(max(次数)-1)*(n+1)+1。其余任务直接插空即可。

代码(Python):

class Solution(object):
    def leastInterval(self, tasks, n):
        """
        :type tasks: List[str]
        :type n: int
        :rtype: int
        """
        output = [0]*26
        for i in tasks:
            output[ord(i)-ord('A')] = output[ord(i)-ord('A')]+1

        count = 0
        len_o = 0
        max_o = max(output)
        for i in output:
            if i==max_o:
                count = count+1
                    
        return max(len(tasks),(max_o-1)*(n+1)+count) 



猜你喜欢

转载自blog.csdn.net/xiaoxiaoley/article/details/79159125