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 intervalnthat 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].
分析
- we schedule the most freqency tasks first(this is the logic of greedy) . we use map to remark each task's frequency
- find the topest frequency, then this task would be our priorty to be scheduled
- calculate how many tasks has the same frequency as the topest one
- the ans would be (n+1) * (k-1) + p
- there is other possibility that we can schedule all the tasks without idling
- then the result would be either ans or tasks' length, whichever is larger
图例
代码
class Solution {
public int leastInterval(char[] tasks, int n) {
// special case
if(tasks.length == 0 ) return 0;
int []map = new int[26];
//标记
for(int i = 0; i< tasks.length; i++){
map[tasks[i]-'A']++;
}
int max = 0;
int p = 0;
//找到频率最高的
for(int i = 0; i< 26; i++){
max = Math.max(max, map[i]);
}
//频率最高的可能被安排到最后
for(int i = 0; i< 26; i++){
if(max==map[i]){
p++;
}
}
int ans = (n+1) * (max-1) + p;
return Math.max(tasks.length, ans);
}
}