| 일 | 월 | 화 | 수 | 목 | 금 | 토 |
|---|---|---|---|---|---|---|
| 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 |
- count
- leetcode
- MySQL
- Navigation
- routes
- Props
- Context
- event
- treenode
- array
- Callback
- DP
- UE5
- server
- state
- priority_queue
- css
- component
- React
- 비트연산
- BinaryTree
- route
- queue
- map
- bit
- JSX
- nodeJS
- node.js
- c++
- axios
- Today
- Total
우사미 코딩
[Leetcode] 621. Task Scheduler 본문
1. 문제링크
https://leetcode.com/problems/task-scheduler/
Task Scheduler - LeetCode
Can you solve this real interview question? 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. F
leetcode.com
2. key point - priority_queue를 사용하자!
1) 각 task의 횟수를 vector에 저장한다
2) 횟수가 1 이상이면 priority_queue에 push한다
3) cycle은 n + 1이다
4) queue에서 하나씩 빼서 1보다 크면 남은 횟수를 캐시해 두었다가 남은 횟수를 다시 queue에 넣어준다
3. solution
class Solution {
public:
int leastInterval(vector<char>& tasks, int n) {
vector<int> v(26, 0);
priority_queue<int> pq;
for(auto i : tasks){
v[i-'A']++;
}
for(int i = 0; i < 26; i++){
if(v[i] > 0)
pq.push(v[i]);
}
int time = 0;
while(!pq.empty()){
int cycle = n + 1;
vector<int> remain;
while(cycle > 0 && !pq.empty()){
int freq = pq.top();
pq.pop();
if(freq > 1){
remain.push_back(freq-1);
}
cycle--;
time++;
}
for(auto i : remain)
pq.push(i);
if(pq.empty())
break;
time += cycle;
}
return time;
}
};'Leetcode' 카테고리의 다른 글
| [Leetcode] 210. Course Schedule II - Topological Sorting (0) | 2023.05.27 |
|---|---|
| [Leetcode] 994. Rotting Oranges - BFS (0) | 2023.05.26 |
| [Leetcode] 33. Search in Rotated Sorted Array - binary search (0) | 2023.05.23 |
| [Leetcode] 437. Path Sum III (0) | 2023.05.23 |
| [Leetcode] 543. Diameter of Binary Tree (0) | 2023.05.23 |