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 1:

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

Note:

  1. The number of tasks is in the range [1, 10000].
  2. The integer n is in the range [0, 100].

一个表示CPU要做的任务数组。用大写字母A到Z来表示,不同的字母表示不同的任务。任务完成顺序不限,每个任务可在一个时间内完成,对于每个时间,CPU可以完成一个任务或空闲。但在两个相同任务之间要有一个冷却时间间隔n,间隔内CPU可以执行其他不同的任务或是处于空闲状态。求CPU完成所有给定任务所需的最小时间。

解法:先用哈希表或者数组对任务出现的次数进行统计,找出任务出现次数的最大值max_count(有可能是多个),然后把这个任务(或者任务对)之间按n个间隔进行分隔排列,然后把其它任务插到这些间隔里面。由于其它任务出现的次数少于max_count所以肯定能放下,如有空位就是需要空闲(idle)。最后,还要注意的是,如果空位都插满之后还有任务,那就随便在这些间隔里面插入就可以,因为间隔长度肯定会大于n,在这种情况下就是任务的总数是最小所需时间。

情况1:AAABBCD,n=2。分隔为:AXXAXXA -> ABCABDA(其中,X表示需要填充任务或者idle的间隔)

情况2:AAAABBBBCCDE,n=3。分隔为:ABXXABXXABXXAB -> ABCDABCEABXXAB 或者 ABCXABCXABDEAB, etc. 此时要加上出现次数也是max_count的任务的个数same_max_count(相当于末尾多了这几个)。

情况3:AAABBCDEF,n=2。分隔为:AXXAXXA -> ABCEABDFA 或者 ABCEABDAF, etc. 此时就是task的长度是最小时间。

最少的任务时间公式:max(len(tasks), (max_count-1) * (n+1) + other_max_count)

Java: O(1) time O(1) space

public class Solution {
public int leastInterval(char[] tasks, int n) {
int[] counter = new int[26];
int max = 0;
int maxCount = 0;
for(char task : tasks) {
counter[task - 'A']++;
if(max == counter[task - 'A']) {
maxCount++;
}
else if(max < counter[task - 'A']) {
max = counter[task - 'A'];
maxCount = 1;
}
} int partCount = max - 1;
int partLength = n - (maxCount - 1);
int emptySlots = partCount * partLength;
int availableTasks = tasks.length - max * maxCount;
int idles = Math.max(0, emptySlots - availableTasks); return tasks.length + idles;
}
}

Java: O(N) time O(26) space 

// (c[25] - 1) * (n + 1) + 25 - i  is frame size
// when inserting chars, the frame might be "burst", then tasks.length takes precedence
// when 25 - i > n, the frame is already full at construction, the following is still valid.
public class Solution {
public int leastInterval(char[] tasks, int n) { int[] c = new int[26];
for(char t : tasks){
c[t - 'A']++;
}
Arrays.sort(c);
int i = 25;
while(i >= 0 && c[i] == c[25]) i--; return Math.max(tasks.length, (c[25] - 1) * (n + 1) + 25 - i);
}
}

Python: O(1) time O(1) space

class Solution(object):
def leastInterval(self, tasks, n):
"""
:type tasks: List[str]
:type n: int
:rtype: int
"""
count = collections.defaultdict(int)
max_count = 0
for task in tasks:
count[task] += 1
max_count = max(max_count, count[task]) result = (max_count-1) * (n+1)
for count in count.values():
if count == max_count:
result += 1
return max(result, len(tasks))   

C++:

class Solution {
public:
int leastInterval(vector<char>& tasks, int n) {
int mx = 0, mxCnt = 0;
vector<int> cnt(26, 0);
for (char task : tasks) {
++cnt[task - 'A'];
if (mx == cnt[task - 'A']) {
++mxCnt;
} else if (mx < cnt[task - 'A']) {
mx = cnt[task - 'A'];
mxCnt = 1;
}
}
int partCnt = mx - 1;
int partLen = n - (mxCnt - 1);
int emptySlots = partCnt * partLen;
int taskLeft = tasks.size() - mx * mxCnt;
int idles = max(0, emptySlots - taskLeft);
return tasks.size() + idles;
}
};

类似题目:

[LeetCode] 358. Rearrange String k Distance Apart 按距离k间隔重排字符串

All LeetCode Questions List 题目汇总

  

[LeetCode] 621. Task Scheduler 任务调度的更多相关文章

  1. [leetcode]621. Task Scheduler任务调度

    Given a char array representing tasks CPU need to do. It contains capital letters A to Z where diffe ...

  2. LeetCode 621. Task Scheduler

    原题链接在这里:https://leetcode.com/problems/task-scheduler/description/ 题目: Given a char array representin ...

  3. [LeetCode]621. Task Scheduler 任务安排 题解

    题目描述 给定一个char数组,代表CPU需要做的任务,包含A-Z,不用考虑顺序,每个任务能在1个单位完成.但是有规定一个非负整数n代表两个相同任务之间需要至少n个时间单位.球最少数量的时间单位完成所 ...

  4. [leetcode] 621. Task Scheduler(medium)

    原题 思路: 按频率最大的字母来分块,频率最大的字母个数-1为分成的块数,每一块个数为n+1 比如AAABBCE,n=2, 则分为A-A- +A AAABBBCCEE,n=2,则分为AB-AB- +A ...

  5. 【LeetCode】621. Task Scheduler 解题报告(Python & C++)

    作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 目录 题目描述 题目大意 解题方法 公式法 日期 题目地址:https://leetco ...

  6. 621. Task Scheduler

    https://www.cnblogs.com/grandyang/p/7098764.html 将个数出现最多的那个字符作为分隔的标准,一定是最小的.所以这个时候只需要计算还需要添加多少个idel就 ...

  7. 621. Task Scheduler CPU任务间隔分配器

    [抄题]: Given a char array representing tasks CPU need to do. It contains capital letters A to Z where ...

  8. SpringBoot2 task scheduler 定时任务调度器四种方式

    github:https://github.com/chenyingjun/springboot2-task 使用@EnableScheduling方式 @Component @Configurabl ...

  9. Spring的任务调度@Scheduled注解——task:scheduler和task:executor的解析

    原文地址: https://blog.csdn.net/yx0628/article/details/80873774 一个简单的Spring定时任务的 demo,全部代码见下载地址:https:// ...

随机推荐

  1. Java并发包--ConcurrentSkipListSet

    https://www.cnblogs.com/kexianting/p/8550459.html import java.util.concurrent.ConcurrentLinkedQueue; ...

  2. git免密

    免账号密码输入 git clone https://lichuanfa%40gitcloud.com.cn:lcf13870752164@git.c.citic/Citic-Data/bigdata_ ...

  3. 基于源代码为树莓派设备构建 TensorFlow

    本指南为运行 Raspbian 9.0 操作系统的 Raspberry Pi 嵌入式设备构建 TensorFlow.虽然这些说明可能也适用于其他系列的 Raspberry Pi 设备,但它仅针对此文中 ...

  4. memoryCache 和 diskCache 的相关总结

    一.缓存位置 在浏览器开发者工具的 Network 的 Size 栏会出现的三种情况: from Service Worker from memory cache from disk cache 真正 ...

  5. pandas 常用方法使用示例

    from pandas import DataFrame import numpy as np import pandas as pd t={ , , np.nan, , np.nan, ], &qu ...

  6. c#中的多态学习总结

    c#的多台方法,大体上和c++的类似,但是有点区别的,我这里刚刚初学,因此把重点记录下. 多态是同一个行为具有多个不同表现形式或形态的能力. 多态性意味着有多重形式.在面向对象编程范式中,多态性往往表 ...

  7. JS优化常用片断

    防抖debounce装饰器 在事件被触发n秒后再执行回调,如果在这n秒内又被触发,则重新计时. function debounce(func, delay) { let isCooldown = fa ...

  8. 六.深浅copy

    先问问大家,什么是拷贝?拷贝是音译的词,其实他是从copy这个英文单词音译过来的,那什么是copy? copy其实就是复制一份,也就是所谓的抄一份.深浅copy其实就是完全复制一份,和部分复制一份的意 ...

  9. “OKR播种机”JOHN DOERR–目标是对抗纷乱思绪的一针疫苗

    OKR培养出疯狂的想法,再加上对的人,奇迹就会出现 约翰·杜尔是美国最有影响力.最具创意.最不拘传统的冒险资本投资家之一.在短短10年内创造了高达1,000亿美元的经济价值.迄今为止,他已向 250家 ...

  10. bg/fg

    将一个在后台暂停的命令,变成继续执行 (在后台执行). 一般ctrl+z就把前台命令调到了后台 将后台中的命令调至前台继续运行