Task Scheduler
Input: tasks = ['A','A','A','B','B','B'], n = 2
Output: 8
Explanation: A -> B -> idle -> A -> B -> idle -> A -> B.Basic Idea:

Last updated
Input: tasks = ['A','A','A','B','B','B'], n = 2
Output: 8
Explanation: A -> B -> idle -> A -> B -> idle -> A -> B.
Last updated
public class Solution {
public int leastInterval(char[] tasks, int n) {
int[] map = new int[26];
for (char c : tasks) {
map[c - 'A']++;
}
Arrays.sort(map);
int i = 25;
while (i >= 0 && map[i] == map[25]) i--;
return Math.max(tasks.length, (map[25] - 1) * (n + 1) + 25 - i);
}
} public class Solution {
public int leastInterval(char[] tasks, int n) {
PriorityQueue<Integer> pq = new PriorityQueue<>(Collections.reverseOrder());
// 统计每种任务的个数,存入pq
int[] map = new int[26];
for (char c : tasks) {
map[c - 'A']++;
}
for (int num : map) {
if (num > 0) pq.offer(num);
}
// 每个周期中,依次执行当前数量最多的几个任务。操作方法就是将任务poll之后,剩余数量存入list,
// 周期结束之后再把list中剩余的任务offer。当list和pq都空时结束。
// 每个周期长度为 n+1
int ret = 0;
while (! pq.isEmpty()) {
int time = 1;
List<Integer> temp = new ArrayList<>();
while (time <= n + 1) {
if (! pq.isEmpty()) {
int remain = pq.poll() - 1;
if (remain > 0) temp.add(remain);
}
ret++; // 更新总步数统计
time++; // 更新当前周期内的步数
if (pq.isEmpty() && temp.isEmpty()) {
// 结束
break;
}
}
pq.addAll(temp);
}
return ret;
}
} class Solution(object):
def leastInterval(self, tasks, n):
"""
:type tasks: List[str]
:type n: int
:rtype: int
"""
counter = [0] * 26
for task in tasks:
counter[ord(task) - ord('A')] += 1
# push all numbers in pq
pq = [(-a, a) for a in counter if a > 0]
heapq.heapify(pq)
# 每个周期中,一次从数量最多的task开始选择,剩余的存入list,周期结束后push回pq
ret = 0
while pq:
lst = []
time = 1
while time <= n + 1:
if pq:
task = heapq.heappop(pq)
if task[1] > 1:
lst.append((task[0] + 1, task[1] - 1))
time += 1
ret += 1
if not pq and not lst:
break
for task in lst:
heapq.heappush(pq, task)
return ret