https://programmers.co.kr/learn/courses/30/lessons/42587
우선순위 큐를 이용해서 풀었다.
일단 priorities 배열을 우선순위 큐에 넣었다.
그러면 큐에서 하나씩 꺼낼때마다 가장 큰 값이 나온다.
다음에 큐가 비어있을 때까지 while문을 돌린다.
while문 안에서 priorities 배열을 loop한다.
큐의 제일 위에값과 priorities의 값을 하나씩 비교해서 같으면 큐에서 값을 하나 빼면서 answer를 1씩 증가시켜 준다.
이때 priorities의 인덱스 값과 location의 값이 일치한다면 answer를 return 시켜준다.
[예제]
2 1 3 2에서 2번 인덱스(3)는 몇번째로 인쇄되는가?
[풀이]
import java.util.*;
class Solution {
public int solution(int[] priorities, int location) {
// 몇번째인지 return 하는 것이므로 1부터 시작(0번째는 없으므로)
int answer = 1;
// 우선순위 큐 생성
PriorityQueue<Integer> queue = new PriorityQueue<>(Collections.reverseOrder());
// 큐에 담아준다.
for (int x : priorities) {
queue.offer(x);
}
// 큐가 비어있지 않을 때까지 loop한다.
while (!queue.isEmpty()) {
// priorities loop
for (int i = 0; i < priorities.length; i++) {
// 큐의 제일 위에값과 priorities[i] 값이 같은지 비교
if (!queue.isEmpty() && priorities[i] == queue.peek()) {
// 만약 i와 location도 같으면 answer return
if (i == location) {
return answer;
}
// 위에서 return 이 안된다면 answer를 증가시켜주고 큐에서 값을 하나 뺀다. (제일 큰 값이 빠지게 된다.)
answer++;
queue.poll();
}
}
}
return answer;
}
}