## 题目描述

``````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.

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

## 代码

### Approach #1

``````// (c[25] - 1) * (n + 1) + 25 - i  is frame size
// when inserting chars, the frame might be "burst", then tasks.length takes precedence
// when 25 - i > n, the frame is already full at construction, the following is still valid.
public class Solution {
public int leastInterval(char[] tasks, int n) {
int[] count = new int[26];
count[t - 'A']++;
}
Arrays.sort(count);

int i = 25;
while(i >= 0 && count[i] == count[25])     i--;
// AB--AB--AB, 25 -i 为最后一个AB长度
return Math.max(tasks.length, (count[25] - 1) * (n + 1) + 25 - i);
// 每块有n+1个
}
}``````

### Approach #2 Sorting

``````class Solution {
public int leastInterval(char[] tasks, int n) {
int[] map = new int[26];
map[c - 'A']++;
}
Arrays.sort(map); // sort
int time = 0;
while (map[25] > 0) {
int i  = 0;
while (i <= n) {
if (map[25] == 0) break;
if (i < 26 && map[25 - i] > 0) {
map[25 - i]--;
}
time++;
i++;
}
Arrays.sort(map);
}
return time;
}
}``````

Last updated