Skip to content

Commit 5e23b80

Browse files
committed
621. Task Scheduler
1 parent c089ef4 commit 5e23b80

File tree

2 files changed

+56
-0
lines changed

2 files changed

+56
-0
lines changed

621. Task Scheduler/Question.md

+23
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
**621. Task Scheduler**
2+
3+
https://leetcode.com/problems/task-scheduler/
4+
5+
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.
6+
7+
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.
8+
9+
You need to return the least number of intervals the CPU will take to finish all the given tasks.
10+
11+
12+
13+
Example:
14+
15+
Input: tasks = ["A","A","A","B","B","B"], n = 2
16+
Output: 8
17+
Explanation: A -> B -> idle -> A -> B -> idle -> A -> B.
18+
19+
20+
Note:
21+
22+
- The number of tasks is in the range [1, 10000].
23+
- The integer n is in the range [0, 100].

621. Task Scheduler/Solution.java

+33
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
/**
2+
* Runtime: 31 ms, faster than 32.09% of Java online submissions for Task Scheduler.
3+
* Memory Usage: 41.9 MB, less than 5.88% of Java online submissions for Task Scheduler.
4+
*/
5+
class Solution {
6+
public int leastInterval(char[] tasks, int n) {
7+
Map<Character, Integer> map = new HashMap<>();
8+
PriorityQueue<Integer> maxHeap = new PriorityQueue<>((a,b) -> b-a);
9+
10+
for (char t: tasks)
11+
map.put(t, map.getOrDefault(t, 0) + 1);
12+
13+
maxHeap.addAll(map.values());
14+
15+
int cycles = 0;
16+
while (!maxHeap.isEmpty()) {
17+
List<Integer> temp = new ArrayList<>();
18+
for (int i = 0; i <= n; i++) {
19+
if (!maxHeap.isEmpty()) {
20+
int v = maxHeap.poll();
21+
if (v > 1)
22+
temp.add(v-1);
23+
}
24+
cycles++;
25+
if (maxHeap.isEmpty() && temp.size() == 0)
26+
break;
27+
}
28+
for (int j : temp)
29+
maxHeap.add(j);
30+
}
31+
return cycles;
32+
}
33+
}

0 commit comments

Comments
 (0)