[Leetcode学习-java]Task Scheduler(任务调度)

问题:

难度:medium

说明:

给出一个任务数组,由 A ~ Z 字符组成,每个字母代表一个任务,CPU 1 单位时间内处理一个任务,然后两个相同任务之间,会有 N 个单位时间阻隔。

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

输入范围:

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

输入案例:

Example 1:
Input: tasks = ["A","A","A","B","B","B"], n = 2
Output: 8
Explanation: 
A -> B -> idle -> A -> B -> idle -> A -> B
There is at least 2 units of time between any two same tasks.

Example 2:
Input: tasks = ["A","A","A","B","B","B"], n = 0
Output: 6
Explanation: On this case any permutation of size 6 would work since n = 0.
["A","A","A","B","B","B"]
["A","B","A","B","A","B"]
["B","B","B","A","A","A"]
...
And so on.

Example 3:
Input: tasks = ["A","A","A","A","A","A","B","C","D","E","F","G"], n = 2
Output: 16
Explanation: 
One possible solution is
A -> B -> C -> A -> D -> E -> A -> F -> G -> A -> idle -> idle -> A -> idle -> idle -> A

我的代码:

就像坐座位一样,把数组里面出现次数最多的元素进行统计,然后就会出现一个座位槽的数量:

比如输入 [A,A,A,B,B,B] , N = 2 有: A - - A - - A - - - - - -(无限) 这样的排列,因为 A 是数组最多元素之一,但是 B也和它一样多,那么入座是这样 A B - A B - A B ,总共 8 个座位。

对,就是坐座位的意思,那么意会就可以了。

class Solution {
    private static int[] num = new int[26];
    
    public int leastInterval(char[] tasks, int n) {
        Arrays.fill(num,0);
        for(char c : tasks) num[c - 'A'] ++; // 先统计所有元素数量
        
        // 找出最大的一个元素,并且统计和它一样大的元素数量
        int max = num[25];
        int maxc = 0;
        int maxIndex = 0;
        for(int i = 25;i -- > 0;) {
            if(max < num[i]) {
                max = num[i];
                maxc = 0;
                maxIndex = i;
            } else if(max == num[i]) maxc ++;
        }
        
        // 然后就是 总数 - 最大元素数量 - 等大数量 - 座位数
        int d =  tasks.length - num[maxIndex] - maxc - (num[maxIndex] - 1) * n;
            d = d > 0 ? d : 0;

        // 此外还需要注意 所有元素只有一个 和 相隔数 N < 等大数量,那就可以完全分配不用插入空座位
        return num[maxIndex] > 1 && n > maxc ? (num[maxIndex] - 1) * n + num[maxIndex] + d + maxc : tasks.length;
    }
}

猜你喜欢

转载自blog.csdn.net/qq_28033719/article/details/107665961