621. Task Scheduler
Problem description:
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 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].
Solution:
- count max frequency
- find how many tasks are max frequency
- calculate the scheduled slots by max frequency. The idea here is we assume the tasks list is max_frequency tasks dominant
- If the scheduled slots is smaller than len(tasks), it means there’re enough tasks to fill out the cooldown interval.
1 | class Solution: |
Solution: Heap
The idea is to find the largest frequency element in the heap
, schedule it in a round, then put it aside in a tmp
(to not schedule it before cooldown time).
If one of the round we have no task in heap
and nothing in tmp
, it means no remaining task, no need to continue.
Otherwise, if no task in heap
but have task in tmp
, it means we have to wait for cooldown.
When end of a round, push the tasks in tmp
back to heap
for next round.
1 | class Solution: |
Solution:
The idea is to count whether if we need extra idle slots.1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20class Solution {
public:
int leastInterval(vector<char>& tasks, int n) {
vector<int> map(26, 0); //only 26 character
for (auto c: tasks)
map[c - 'A']++; //count which task has the largest frequency
sort(map.begin(), map.end());
int max_val = map[25] - 1; //last element do not need cool down
int idle_slots = max_val * n;
for (int i = 24; i >= 0 && map[i] > 0; i--) {
//already set up the largest one, so start at i=24
idle_slots -= min(map[i], max_val);
}
//if idle slot > 0, some of the task need extra.
//idle slot < 0, don't need idle slots
return idle_slots > 0 ? idle_slots + tasks.size() : tasks.size();
}
};
Second time
1 | class Solution { |
Third time:
Use a vector to count every appeared character.
Sort the vector, it will be ascending order; therefore, the largest element would be in the last.
1 | class Solution { |
reference:
https://goo.gl/DaFYrA
https://goo.gl/unPm4P
https://goo.gl/JhFQuh