[leetcode]621. Task Scheduler任务调度

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:

Input: tasks = ["A","A","A","B","B","B"], n = 2
Output: 8
Explanation: A -> B -> idle -> A -> B -> idle -> A -> B.

代码

 1 class Solution {
 2     public int leastInterval(char[] tasks, int n) {
 3         // corner
 4         if( tasks == null || tasks.length == 0 ) return 0;  
 5         // simplified edition of hashmap
 6         int []map = new int[26]; 
 7         
 8         //remark every character's frequency
 9         for(int i = 0; i< tasks.length; i++){  
10             map[tasks[i]-'A']++;
11         }
12         
13         int max = 0; 
14         int c = 0;  
15         
16         //找到频率最高的
17         // find the toppest frequency 
18         for(int i = 0; i< 26; i++){ 
19             max = Math.max(max, map[i]); // update the max while traversing 
20         }
21         
22         //频率最高的可能被安排到最后
23         // maybe there is not only one toppest frequency
24          for(int i = 0; i< 26; i++){ 
25             if(max == map[i]){ 
26                 c++;
27             }
28         }
29         
30         int ans = (n+1) * (max-1) + c;
31         /* there is other possibility that we can schedule all the tasks  without idling , then the max would be tasks.length */  
32         return Math.max(tasks.length, ans);  
33     }
34 }


原文地址:https://www.cnblogs.com/liuliu5151/p/9808256.html