621. Task Scheduler

Description

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:

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

Solution

Greedy

这道题显然需要用Greedy去做,优先做出现频率高的task。原本想构造一个Tuple class存储某类task下一个预期的执行时间,但是发现有问题,考虑这个例子:
[a,a,a,b,c,d], n = 2
队列里面一开始存储的是(a, 3, 1), (b, 1, 1), (c, 1, 1), (d, 1, 1)
那么首先做完一个task a之后,(a, 2, 4)重新入队列,接下来会做task b和task c,然后这种算法下面会做task d,而不是task a!所以这样做不行。

后来发现并不需要estimate time,将时间分段来看,每段长度为n + 1,然后往每个时间片上添任务就行了。这样一定可以保证每个时间片内相同的任务之间的距离至少是n。

class Solution {
    public int leastInterval(char[] tasks, int n) {
        Map<Character, Integer> freq = new HashMap<>();
        for (char task : tasks) {
            freq.put(task, freq.getOrDefault(task, 0) + 1);
        }
        
        PriorityQueue<Map.Entry<Character, Integer>> queue 
            = new PriorityQueue<>((a, b) -> b.getValue() - a.getValue());
        queue.addAll(freq.entrySet());
        
        int time = 0;
        while (!queue.isEmpty()) {
            int k = n + 1;
            List<Map.Entry<Character, Integer>> tmpList = new LinkedList<>();
            
            while (k > 0 && !queue.isEmpty()) {
                Map.Entry<Character, Integer> entry = queue.poll();
                ++time;     // one task executed
                --k;
                entry.setValue(entry.getValue() - 1);
                if (entry.getValue() > 0) {
                    tmpList.add(entry);
                }
            }
            
            queue.addAll(tmpList);  // add tasks back to queue
            if (!queue.isEmpty()) {
                time += k;  // idle time
            }
        }
        
        return time;
    }
}
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容