[Level2] 프로세스
프로그래머스
SW개발자를 위한 평가, 교육, 채용까지 Total Solution을 제공하는 개발자 성장을 위한 베이스캠프
programmers.co.kr
문제 이해

→ 프로세스의 값이 아님 위치로 판단해야 함
슈도 코드
1. 큐(queue)와 우선순위(priority queue)를 초기화한다.
- queue: (인덱스, 우선순위) 형태로 저장
- priorityQueue: 우선순위 값들만 저장 (내림차순 정렬)
2. 반복문을 실행하면서 다음을 수행:
- queue에서 (현재 인덱스, 현재 우선순위)를 poll()
- 현재 우선순위가 priorityQueue에서 가장 높은 값과 같은지 비교:
- 같다면 실행 (answer += 1)
- 목표 인덱스이면 종료하고 answer 반환
- 다르면 다시 queue에 추가
참고한 부분
// 큐에 배열로 저장 가능
Queue<int[]> queue = new LinkedList<>();
queue.add(new int[]{i, priorities[i]});
// 우선순위 큐
// 기본형: 우선순위가 낮은 숫자 먼저 (오름차순)
PriorityQueue<Integer> pQueue = new PriorityQueue<>();
// 우선순위가 높은 숫자 먼저(내림차순)
PriorityQueue<Integer> pQueue = new PriorityQueue<>(Collections.reverseOrder());
전체 코드
import java.util.*;
class Solution {
public int solution(int[] priorities, int location) {
int answer = 0;
Queue<int[]> queue = new LinkedList<>();
PriorityQueue<Integer> pQueue = new PriorityQueue<>(Collections.reverseOrder());
// 큐 초기화
for (int i = 0; i < priorities.length; i++) {
queue.add(new int[]{i, priorities[i]});
pQueue.add(priorities[i]);
}
while (!queue.isEmpty()) {
int[] top = queue.poll();
// 우선순위가 제일 높은 값이면
if (top[1] == pQueue.peek()) {
pQueue.poll(); // 실행했으므로 제거
answer++; // 실행 순서 증가
// 현재 인덱스가 목표 위치의 값이면 return
if (top[0] == location) {
return answer;
}
} else {
queue.add(top); // 우선순위가 아니면 다시 add
}
}
return answer;
}
}
'코딩테스트 > 프로그래머스' 카테고리의 다른 글
[JAVA] 프로그래머스 Level2. 더 맵게 (0) | 2025.03.02 |
---|