LeetCode 621: Task Scheduler

Posted keepshuatishuati

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了LeetCode 621: Task Scheduler相关的知识,希望对你有一定的参考价值。

class Solution {
    class Task {
        public char task;
        public int numTasks;
    }
    public int leastInterval(char[] tasks, int n) {
        if (tasks.length == 0) {
            return 0;
        }

        Map<Character, Task> map = new HashMap<>();
        for (char c : tasks) {
            if (!map.containsKey(c)) {
                Task t = new Task();
                t.task = c;
                t.numTasks = 0;
                map.put(c, t);
            }
            map.get(c).numTasks++;
        }
        Queue<Task> queue = new PriorityQueue<>((t1, t2) -> t2.numTasks - t1.numTasks);
        queue.addAll(map.values());
        int result = 0;
        while (!queue.isEmpty()) {
            int k = n + 1;
            List<Task> taskList = new ArrayList<>();
            while (k > 0 && !queue.isEmpty()) {
                Task current = queue.poll();
                current.numTasks--;
                taskList.add(current);
                result++;
                k--;
            }
            
            for (Task task : taskList) {
                if (task.numTasks > 0) {
                    queue.offer(task);
                }
            }
            if (queue.isEmpty()) break;
            result += k;
        }
        return result;
    }
}

 

以上是关于LeetCode 621: Task Scheduler的主要内容,如果未能解决你的问题,请参考以下文章

LeetCode 621: Task Scheduler

[leetcode]Queue-621. Task Scheduler

leetcode621 - Task Scheduler - medium

[leetcode]621. Task Scheduler任务调度

[LeetCode] 621. Task Scheduler

621. Task Scheduler