728x90
반응형
[문제 링크]
프로그래머스
SW개발자를 위한 평가, 교육의 Total Solution을 제공하는 개발자 성장을 위한 베이스캠프
programmers.co.kr
[문제]

입출력 예
| priorities | location | return |
| [2, 1, 3, 2] | 2 | 1 |
| [1, 1, 9, 1, 1, 1] | 0 | 5 |
📍 [코드]
import java.util.*;
/*
1. 우선 순위와 인덱스 큐에 저장
2. 우선 순위 기준으로 내림차순 정렬
3. 정렬된 리스트를 순회하면서:
- 실제 큐에서 문서를 하나씩 꺼낸다
- 그 문서가 정렬 리스트의 현재 값과 같으면 count++
- 해당 문서의 인덱스가 location과 같으면 return count
*/
class Solution {
public int solution(int[] priorities, int location) {
int count = 0;
//큐 (인덱스, 우선순위)
Queue<int[]> queue = new LinkedList<>();
for (int i = 0; i < priorities.length; i++) {
queue.offer(new int[]{i, priorities[i]});
}
//우선순위 내림차순 정렬 리스트 생성
List<Integer> sortedPriorities = new ArrayList<>();
for (int p : priorities) {
sortedPriorities.add(p);
}
sortedPriorities.sort(Collections.reverseOrder()); // 내림차순 정렬
int priorityIndex = 0; // 현재 처리할 우선순위 인덱스
while (!queue.isEmpty()) {
int[] current = queue.poll(); // [index, priority]
if (current[1] == sortedPriorities.get(priorityIndex)) {
count++;
if (current[0] == location) {
return count;
}
priorityIndex++; // 다음 우선순위로
} else {
queue.offer(current); // 다시 뒤로 보냄
}
}
return count; // 도달 불가능
}
}
💡 접근법
✅ Queue 사용
- 우선 순위와 인덱스 큐에 저장
- 우선 순위 기준으로 내림차순 정렬
- 정렬된 리스트를 순회하면서:
- 실제 큐에서 문서를 하나씩 꺼낸다.
- 그 문서가 정렬 리스트의 현재 값과 같으면
count++ - 해당 문서의 인덱스가
location과 같으면return count
📚 코드 흐름 설명
- priorityIndex = 0 → 현재 확인할 "가장 높은 우선순위"는 3
Step 1️⃣
poll()→[0,2]- 현재
priority = 2, 최고 우선순위 = 3 - ❌ 같지 않음 → 뒤로 보냄
queue = [[1,1], [2,3], [3,2], [0,2]]
Step 2️⃣
poll()→[1,1]- 현재
priority = 1, 최고 우선순위 = 3 - ❌ 다시 뒤로 보냄
queue = [[2,3], [3,2], [0,2], [1,1]]
Step 3️⃣
poll()→[2,3]- 현재
priority = 3, 최고 우선순위 = 3 - ✅ 일치 → count 증가
count = 1
priorityIndex = 1 (다음 최고 우선순위 = 2)
그리고 현재 문서 인덱스 = 2
찾던 location = 2와 같음 → return 1
💬 마무리
이 문제를 풀며 아직 내가 Queue를 다루는 게 미흡하구나를 깨달았다.
또한, 코드가 길어지는 것을 두려워하지 않는 마인드도 필요한 것 같다.
728x90
반응형
