처음에는 LinkedList를 이용하여 해결하려고 했는데 쉽지 않았다.
다른 사람들의 풀이를 확인해보니 우선순위 큐를 이용하여 쉽게 해결할 수 있다는 것을 알게 되었다.
우선순위 큐
//낮은 숫자가 우선 순위인 int 형 우선순위 큐 선언
PriorityQueue<Integer> priorityQueueLowest = new PriorityQueue<>();
//높은 숫자가 우선 순위인 int 형 우선순위 큐 선언
PriorityQueue<Integer> priorityQueueHighest = new PriorityQueue<>(Collections.reverseOrder());
이 문제 에서는 우선순위가 높은 프로세스가 먼저 처리 되어야 하므로 높은 숫자가 우선 순위인 우선순위 큐를 사용해야 한다.
PriorityQueue<Integer> pq = new PriorityQueue<>(Collections.reverseOrder());
<우선순위 탐색>
while(!pq.isEmpty()) {
for(int i=0; i<priorities.length; i++) {
if(priorities[i] == pq.peek()) {
pq.poll();
answer++;
if(i == location)
return answer;
}
}
}
priorities배열을 순회 하면서 우선순위가 가장 높은 pq.peek()값과 같을때 그게 location의 위치와 동일하면 answer를 리턴해주고 위치가 location과 다르다면 pq.poll()을 이용해 다음 우선순위를 탐색한다.
<전체 코드>
import java.util.*;
class Solution {
public int solution(int[] priorities, int location) {
int answer = 0;
PriorityQueue<Integer> pq = new PriorityQueue<>(Collections.reverseOrder());
for(int num : priorities) {
pq.add(num);
}
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;
}
}
'알고리즘 > 스택 큐' 카테고리의 다른 글
프로그래머스 - 주식가격[Java] (1) | 2025.03.12 |
---|---|
프로그래머스 - 다리를 지나는 트럭[Java] (0) | 2025.03.09 |
프로그래머스 - 올바른 괄호(Java) (0) | 2025.01.02 |
프로그래머스 - 기능개발(Java) (0) | 2025.01.01 |
프로그래머스 - 같은 숫자는 싫어(Java) (1) | 2024.12.31 |