42587 - 프로세스
info
- 문제 보기: 42587 - 프로세스
- 소요 시간: 12분 38초
- 풀이 언어:
java
- 체감 난이도: 2️⃣
- 리뷰 횟수: ✅
풀이 키워드
스포주의
큐
정렬
풀이 코드
info
- 메모리: 95700 KB
- 시간: 2 ms
import java.util.*;
class Solution {
public int solution(int[] priorities, int location) {
PriorityQueue<Process> pq = new PriorityQueue<>((a, b) -> b.priority - a.priority);
Deque<Process> dq = new ArrayDeque<>();
for (int i = 0; i < priorities.length; ++i) {
Process p = new Process(i, priorities[i]);
pq.add(p);
dq.add(p);
}
int ans = 1;
while (true) {
Process p = dq.pop();
if (p.priority == pq.peek().priority) {
if (p.id == location) return ans;
else {
pq.poll();
++ans;
}
}
else {
dq.add(p);
}
}
}
class Process {
int id;
int priority;
Process(int id, int priority) {
this.id = id;
this.priority = priority;
}
}
}
풀이 해설
큐를 이용한 간단한 시뮬 문제이다.
빠른 우선순위 판별을 위해 PriorityQueue
를 사용했고, 프로세스는 클래스화했다.
메모
- 쉬움. 이것보단 복잡한 custom comparator 연습이 필요함.
- 그냥 우선순위만 모아서 한번 정렬하고 인덱스로 접근해도 된다. 하지만 자바스럽지 않다.
- 막줄에 return문 쓰면 unreachable statement 에러가 뜬다. while 내에서 return 못해도 pop 같은 곳에서 예외처리로 빠지니까 그런듯.