Leetcode 621 Task Scheduler

本文深入解析了LeetCode上的621题——任务调度器,探讨了三种解决方案:排序法、优先队列法及计算空闲槽法。通过具体案例,展示了如何优化任务调度,减少等待时间,提高效率。

Leetcode 621 Task Scheduler

Approach #1 Using Sorting [Accepted]
But, there is a flaw in the above idea. Consider the case, where say the number of instances of tasks A, B, C, D, E are 6, 1, 1, 1, 1 respectively with n=2(cooling time). If we go by the above method, firstly we give 1 round to each A, B, C, D and E. Now, only 5 instances of A are pending, but each instance will take 3 time units to complete because of cooling time. But a better way to schedule the tasks will be this: A, B, C, A, D, E, … . In this way, by giving turn to the task A as soon as its cooling time is over, we can save a good number of clock cycles.

Note:
It contains capital letters A to Z where different letters represent different tasks.

		int[] map = new int[26];
        for (char c: tasks)
            map[c - 'A']++;
        Arrays.sort(map);

Approach #2 Using Priority-Queue [Accepted]

 		int[] map = new int[26];
        for (char c: tasks)
            map[c - 'A']++;
        PriorityQueue < Integer > queue = new PriorityQueue < >(26,Collections.reverseOrder());
        for (int f: map) {
            if (f > 0)
                queue.add(f);
        }

Approach #3 Calculating Idle slots [Accepted]
We can observe that the maximum number of idle slots will always be given by the product of the cooling time and the number of instances of the task with maximum count less 1.

For example 1:

Input: tasks = [“A”,“A”,“A”,“B”,“B”,“B”,“C”, “C”, " D"], n = 2
Output: 9

[A, B, C]
[A, B, C]
[A, B]
[D, idle]

return tasks.length

Input: tasks = [“A”,“A”,“A”,“B”,“B”], n = 2
Output: 7

[A, B, idle]
[A, B, idle]
[A, idle, idle]

public class Solution {
    public int leastInterval(char[] tasks, int n) {
        int[] map = new int[26];
        for (char c: tasks)
            map[c - 'A']++;
        Arrays.sort(map);
        int max_val = map[25] - 1, idle_slots = max_val * n;
        for (int i = 24; i >= 0 && map[i] > 0; i--) {
            idle_slots -= Math.min(map[i], max_val);
        }
        return idle_slots > 0 ? idle_slots + tasks.length : tasks.length;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值