Leetcode 621. Task Scheduler

来源:互联网 发布:linux for qq2016安装 编辑:程序博客网 时间:2024/06/07 03:01

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 = 2Output: 8Explanation: A -> B -> idle -> A -> B -> idle -> A -> B.

我们要用一个hashmap 来储存 每个字符和出现次数的映射关系,priority queue 来记录出现次数。

n = 2 是, 每次都是 3个 3个 地出现,所以cycle 是 3. 如果 pq 不为 空, 把 pq 最大的 n 个加入到pq 中,同时worktime 加一, 再把 每个 - 1 加回到pq 里。pq 还有书的话,则要加上 一个 cycle, 反之只用加上 worktime。

public int leastInterval(char[] tasks, int n) {                Map<Character, Integer> map = new HashMap<>();        for (char t : tasks) map.put(t, map.getOrDefault(t, 0) + 1);        Queue<Integer> pq = new PriorityQueue<>((a, b) -> b - a);        pq.addAll(map.values());        int res = 0;        int cycle = n + 1;        while (!pq.isEmpty()) {            int worktime = 0;            List<Integer> tmp = new ArrayList<>();            for (int i = 0; i < cycle; i++) {                if (!pq.isEmpty()) {                    tmp.add(pq.poll());                    worktime++;                }            }            for (int cnt : tmp) {                if (--cnt > 0) pq.offer(cnt);            }            res += !pq.isEmpty() ? cycle : worktime;        }        return res;    }








原创粉丝点击