[LeetCode] Task Scheduler

621. Task Scheduler

Given a characters array tasks, representing the tasks a CPU needs to do, where each letter represents a different task. Tasks could be done in any order. Each task is done in one unit of time. For each unit of time, the CPU could complete either one task or just be idle.

However, there is a non-negative integer n that represents the cooldown period between two same tasks (the same letter in the array), that is that there must be at least n units of time between any two same tasks.

Return the least number of units of times that the CPU will take to finish all the given tasks.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
class Solution {
public:
int leastInterval(vector<char>& tasks, int n) {
if(!n) return tasks.size();
queue<tuple<char, int, int>> delay;
priority_queue<pair<int, char>> pq;
unordered_map<char, int> m;
for(auto& c : tasks){
m[c]++;
}
for(auto& e : m) {
pq.push({e.second, e.first});
}

int res = 0;
while(!pq.empty() || !delay.empty()) {
if(!delay.empty() && get<2>(delay.front()) + n < res) {
pq.push({get<1>(delay.front()), get<0>(delay.front())});
delay.pop();
}
if(!pq.empty()) {
auto p = pq.top();
pq.pop();
if(p.first != 1) {
delay.push({p.second, p.first - 1, res});
}
}

res++;
}
return res;
}
};
1
2
3
4
5
6
7
8
9
10
11
12
13
14
class Solution {
public:
int leastInterval(vector<char>& tasks, int n) {
if(!n) return tasks.size();
unordered_map<char, int> m;
unordered_map<int, int> st;
int maxCnt = 0;
for(auto& c : tasks){
maxCnt = max(maxCnt, ++m[c]);
st[m[c]]++;
}
return max((int)tasks.size(), (maxCnt - 1) * (n + 1) + st[maxCnt]);
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2021/05/12/PS/LeetCode/task-scheduler/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.