💡 문제
💬 입출력 예시
📌 풀이(소스코드)
import java.util.*;
class Solution {
public int solution(int[] priorities, int location) {
int answer = 0;
PriorityQueue<Integer> pq = new PriorityQueue<>(Collections.reverseOrder());
for (int priority: priorities) {
pq.offer(priority);
}
while(!pq.isEmpty()) {
for(int i = 0; i < priorities.length; i++) {
if (priorities[i] == pq.peek()) {
pq.poll();
answer++;
if (i == location) {
return answer;
}
}
}
}
return answer;
}
}
📄 해설
접근
- 우선순위 큐를 이용하여 해결하는 문제
- 처음에 인덱스 번호와 우선순위를 멤버 변수로 갖는
Process
라는 클래스를 만들어 접근했는데, 풀다보니 그냥 우선순위 값만 알고 있으면 된다는 것을 알았음
- 우선순위 큐를 역순으로 정렬해두고, 현재 큐의 헤드(가장 높은 우선순위) 값과 일치하는 프로세스를 모두 수행해버리면서
location
에 해당하는 인덱스면 탐색을 종료하면 된다.
과정
- 우선순위 큐를 초기화한다. 이때, 역순으로 초기화하기 위해
Collections.reverseOrder()
를 사용한다.
priorities
의 값을 우선순위 큐에 넣는다.
- 우선순위 큐가 빌 때까지 내부에서
priorities
를 탐색한다. 과정은 아래와 같다.
- 현재 우선순위 값이 큐의 헤드와 일치한지 확인한다.
- 일치하면 해당 노드를 큐에서 제거하고,
answer
값을 증가시킨 후, 인덱스 번호가 location
과 같은지를 확인한다.