[LeetCode] Task Scheduler 任务行程表

版权声明:作者:Britesun 欢迎转载,与人分享是进步的源泉! https://blog.csdn.net/qq_34807908/article/details/81904968

题目

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:

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

分析题目

本题让我们安排CPU的任务,规定在两个相同任务之间至少隔n个时间点。由于题目中规定了两个相同任务之间至少隔n个时间点,那么我们首先应该处理的出现次数最多的那个任务,先确定好这些高频任务,然后再来安排那些低频任务。如果任务F的出现频率最高,为k次,那么我们用n个空位将每两个F分隔开,然后我们按顺序加入其他低频的任务,来看一个例子:

AAAABBBEEFFGG 3

我们发现任务A出现了4次,频率最高,于是我们在每个A中间加入三个空位,如下:

A—A—A—A

AB–AB–AB–A (加入B)

ABE-ABE-AB–A (加入E)

扫描二维码关注公众号,回复: 2930731 查看本文章

ABEFABE-ABF-A (加入F,每次尽可能填满或者是均匀填充)

ABEFABEGABFGA (加入G)

再来看一个例子:

ACCCEEE 2

我们发现任务C和E都出现了三次,那么我们就将CE看作一个整体,在中间加入一个位置即可:

CE-CE-CE

CEACE-CE (加入A)

注意最后面那个idle不能省略,不然就不满足相同两个任务之间要隔2个时间点了。

这道题好在没有让我们输出任务安排结果,而只是问所需的时间总长,那么我们就想个方法来快速计算出所需时间总长即可。我们仔细观察上面两个例子可以发现,都分成了(mx - 1)块,再加上最后面的字母,其中mx为最大出现次数。比如例子1中,A出现了4次,所以有A—模块出现了3次,再加上最后的A,每个模块的长度为4。例子2中,CE-出现了2次,再加上最后的CE,每个模块长度为3。我们可以发现,模块的次数为任务最大次数减1,模块的长度为n+1,最后加上的字母个数为出现次数最多的任务,可能有多个并列。这样三个部分都搞清楚了,写起来就不难了,我们统计每个大写字母出现的次数,然后排序,这样出现次数最多的字母就到了末尾,然后我们向前遍历,找出出现次数一样多的任务个数,就可以迅速求出总时间长了,参见代码如下:

代码

Complexity - Time: O(n), Space: O(1) //使用恒定大小(26)的cnt数组

public class Solution {
    public int leastInterval(char[] tasks, int n) {
        int[] cnt = new int[26];
        for (char c: tasks)
            cnt[c - 'A']++;
        Arrays.sort(cnt);
        int i = 25, mx = cnt[25], len = tasks.length;
        while (i >= 0 && cnt[i] == mx) --i;
        return Math.max(len, (mx - 1) * (n + 1) + 25 - i);
    }
}

猜你喜欢

转载自blog.csdn.net/qq_34807908/article/details/81904968