LeetCode打卡:621. 任务调度器

给定一个用字符数组表示的 CPU 需要执行的任务列表。其中包含使用大写的 A - Z 字母表示的26 种不同种类的任务。任务可以以任意顺序执行,并且每个任务都可以在 1 个单位时间内执行完。CPU 在任何一个单位时间内都可以执行一个任务,或者在待命状态。

然而,两个相同种类的任务之间必须有长度为 n 的冷却时间,因此至少有连续 n 个单位时间内 CPU 在执行不同的任务,或者在待命状态。

你需要计算完成所有任务所需要的最短时间。

示例 :

输入:tasks = [“A”,“A”,“A”,“B”,“B”,“B”], n = 2
输出:8
解释:A -> B -> (待命) -> A -> B -> (待命) -> A -> B.
在本示例中,两个相同类型任务之间必须间隔长度为 n = 2 的冷却时间,而执行一个任务只需要一个单位时间,所以中间出现了(待命)状态。

链接:https://leetcode.com/problems/task-scheduler/

解题思路:
法一:排序思想,每n+1次为一轮,降序遍历排序数组。

class Solution(object):
    def leastInterval(self, tasks, n):
        """
        :type tasks: List[str]
        :type n: int
        :rtype: int
        """
        l = len(tasks)
        if l <= 1:
            return l
        arr = [0] * 26
        for t in tasks:
            arr[ord(t) - ord('A')] += 1
        arr.sort()
        res = 0
        
        # 次数最高为1时跳出循环
        while arr[-1] != 1:
            i = 1
            while i <= n + 1:   # 每n + 1个时间单位为1轮
                res += 1
                if i <= 26 and arr[-i] :
                    arr[-i] -= 1
                i += 1
            arr.sort()          # 每轮完成后重新排序
        for i in range(25, -1, -1):
            if arr[i] == 1:
                res += 1
            else:
                return res
        

法二:桶思想

class Solution(object):
    def leastInterval(self, tasks, n):
        """
        :type tasks: List[str]
        :type n: int
        :rtype: int
        """
        # 桶思想
        l = len(tasks)
        if l <= 1:
            return l
        h = {}
        max_ = 0
        first_max_cnt = 0
        # 找出最大次数
        for t in tasks:
            if t not in h:
                h[t] = 1
            else:
                h[t] += 1
            max_ = max(max_, h[t])
        # 找出有多少个并列最多的任务,即最后一个桶的任务
        for key in h:
            if h[key] == max_:
                first_max_cnt += 1
        
        return max((max_ - 1)*(n + 1) + first_max_cnt, l)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值