Leetcode-Medium 621. Task Scheduler

简介: Leetcode-Medium 621. Task Scheduler

题目描述


给定一个char数组表示CPU需要执行的任务。它包含大写字母A到Z,其中不同的字母代表不同的任务。每项任务都可以在一个时间间隔内完成。对于每个间隔,CPU可以完成一个任务或空闲。但是有规定一个非负整数n代表两个相同任务之间需要至少n个时间单位。球最少数量的时间单位完成所有任务。


需要返回CPU将完成所有给定任务所需的最少间隔数。

实例:


Input: tasks = ["A","A","A","B","B","B"], n = 2
Output: 8
Explanation: A -> B -> idle -> A -> B -> idle -> A -> B.


思路


dicussion 分享的思路concise Java Solution O(N) time O(26) space,通过分析人物队列的规律来计算:

首先考虑出现次数最多的字符,我们可以先确定它们的相对位置,然后将它们用作框架来插入剩余的不常用的字符


65.png



通过上面的分析,我们可以发现最少任务时间为:(最多任务数-1)*(n + 1) + (相同最多任务的任务个数)。

假设AAAABBBBCCDE,n=3,那么时间为:(NUM(A)-1)*(3+1)+2=14


代码实现



class Solution:
    def leastInterval(self, tasks: List[str], n: int) -> int:
        c=collections.Counter(tasks)
        mc,tie_ct=c.most_common(1)[0][1],0
        for k,v in c.most_common()[1:]:
            if v==mc:
                tie_ct+=1
            else:
                break
        return max(len(tasks),(mc-1)*n+mc+tie_ct)


参考资料



相关文章
|
17天前
|
Kubernetes 容器
Warning FailedScheduling 14m (x12 over 16m) default-scheduler 0/1 nodes are available: 1 node(s
Warning FailedScheduling 14m (x12 over 16m) default-scheduler 0/1 nodes are available: 1 node(s
54 0
|
17天前
|
资源调度
在SchedulerX中,你可以使用`schedulerx.output()`函数来向Worker报告运行结果
【1月更文挑战第7天】【1月更文挑战第35篇】在SchedulerX中,你可以使用`schedulerx.output()`函数来向Worker报告运行结果
22 1
|
10月前
|
数据库
This scheduler instance (XXXXX) is still active but was recovered by another
This scheduler instance (XXXXX) is still active but was recovered by another
173 0
|
索引
LeetCode 207. Course Schedule
现在你总共有 n 门课需要选,记为 0 到 n-1。 在选修某些课程之前需要一些先修课程。 例如,想要学习课程 0 ,你需要先完成课程 1 ,我们用一个匹配来表示他们: [0,1] 给定课程总量以及它们的先决条件,判断是否可能完成所有课程的学习?
62 0
LeetCode 207. Course Schedule
|
数据库
This scheduler instance is still active but was recovered by another instance in the cluster
This scheduler instance is still active but was recovered by another instance in the cluster
442 0
|
机器学习/深度学习 算法 Java
[LeetCode] Task Scheduler 任务行程表
Given a char array representing tasks CPU need to do. It contains capital letters A to Z where different letters represent different tasks.
1234 0