forked from KnowledgeCenterYoutube/LeetCode
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path621_Task_Scheduler
More file actions
63 lines (58 loc) · 1.68 KB
/
Copy path621_Task_Scheduler
File metadata and controls
63 lines (58 loc) · 1.68 KB
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
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
Leetcode 621: Task Scheduler
Detailed video explanation: https://youtu.be/tGw5GbDekTU
============================================
C++:
----
class Solution {
public:
int leastInterval(vector<char>& tasks, int n) {
unordered_map<char, int> counts;
for(char t: tasks)
counts[t]++;
priority_queue<int> pq;
for(auto c: counts)
pq.push(c.second);
int result = 0;
while(!pq.empty()){
int time = 0;
vector<int> tmp;
for(int i = 0; i < n+1; ++i){
if(!pq.empty()){
tmp.push_back(pq.top() - 1);
pq.pop();
time++;
}
}
for(auto t: tmp)
if(t) pq.push(t);
result += pq.empty() ? time : n+1;
}
return result;
}
};
Java:
----
class Solution {
public int leastInterval(char[] tasks, int n) {
Map<Character, Integer> counts = new HashMap();
for(char t: tasks)
counts.put(t, counts.getOrDefault(t, 0) + 1);
PriorityQueue<Integer> pq = new PriorityQueue(counts.size(), Collections.reverseOrder());
pq.addAll(counts.values());
int result = 0;
while(!pq.isEmpty()){
int time = 0;
List<Integer> tmp = new ArrayList();
for(int i = 0; i < n+1; ++i){
if(!pq.isEmpty()){
tmp.add(pq.remove() - 1);
time++;
}
}
for(int t: tmp)
if(t > 0) pq.add(t);
result += pq.isEmpty() ? time : n+1;
}
return result;
}
}