LeetCode 621. Task Scheduler
原题链接在这里:https://leetcode.com/problems/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:
- The number of tasks is in the range [1, 10000].
- The integer n is in the range [0, 100].
题解:
类似Rearrange String k Distance Apart.
想要最少的interval完成所有task, 需要先去完成frequency最高的task.
用maxHeap找出frequency 高的task.
然后挨个去执行, 把执行过的task frequency -1.
同时间隔n也递减. 如果n减为0. 说明间隔达到要求, 可以把执行过的task 如果frequency 还是大于0的放回到maxHeap中.
如果n还没尖刀0, maxHeap就空了, 就需要idle来补位. 之后再把执行过的task 如果frequency 还是大于0的放回到maxHeap中.
Time Complexity: O(task.length). 每个task都执行了一遍, 中间多出的idle interval都是通过计算一次加进count中. 最多加最大frequency次idle interval 进count. It uses maxHeap, but maxHeap size maximum is 26.
Space: O(1). map的size最大26.
AC Java:
1 class Solution { 2 public int leastInterval(char[] tasks, int n) { 3 if(tasks == null || tasks.length == 0){ 4 return 0; 5 } 6 7 HashMap<Character, Integer> hm = new HashMap<Character, Integer>(); 8 for(char c : tasks){ 9 hm.put(c, hm.getOrDefault(c,0)+1); 10 } 11 12 PriorityQueue<Map.Entry<Character, Integer>> maxHeap = new PriorityQueue<Map.Entry<Character, Integer>>( 13 (a, b) -> b.getValue() - a.getValue() 14 ); 15 maxHeap.addAll(hm.entrySet()); 16 17 int count = 0; 18 while(!maxHeap.isEmpty()){ 19 LinkedList<Map.Entry<Character, Integer>> que = new LinkedList<Map.Entry<Character, Integer>>(); 20 int k = n+1; 21 while(k > 0 && !maxHeap.isEmpty()){ 22 Map.Entry<Character, Integer> cur = maxHeap.poll(); 23 cur.setValue(cur.getValue()-1); 24 que.add(cur); 25 k--; 26 count++; 27 } 28 29 for(Map.Entry<Character, Integer> entry : que){ 30 if(entry.getValue() > 0){ 31 maxHeap.add(entry); 32 } 33 } 34 35 if(maxHeap.isEmpty()){ 36 break; 37 } 38 39 count += k; // k != 0 要添加idle interval 40 } 41 return count; 42 } 43 }