자료구조나 알고리즘에 대해 공부하고 문제를 풀어보면서 블로그에도 작성해본다.
import java.util.*;
class QueueSolution {
public static void main(String[] args) {
int[] priorities = {2, 1, 3, 2};
int location = 2;
QueueSolution solution = new QueueSolution();
int answer = solution.solution(priorities, location);
System.out.println(answer);
}
public int solution(int[] priorities, int location) {
int answer = 0;
Queue queue = new PriorityQueue(Collections.reverseOrder()); // 1번 테스트케이스에선 queue는 지금 3, 2, 2, 1 으로 들어가 있다.
for (int priority : priorities) {
queue.offer(priority);
}
while (!queue.isEmpty()) { // for 문 1번으로는 한 번밖에 안 돈다
for (int i = 0; i < priorities.length; i++) { // 사이즈만큼 반복
if (queue.element().equals(priorities[i])) {
queue.poll();
answer++;
if (i == location) return answer;
}
}
}
return answer;
}
}
1번 테스트케이스를 가지고 해보았다.
일단은 우선순위 -> 라는 단어를 보고 PriorityQueue 을 구현해야겠다고 생각했다.
그리고 숫자가 클수록 우선순위가 높다고 하였으므로
Queue queue = new PriorityQueue(Collections.reverseOrder());
를 활용하여 역순으로 나타냈다.
1번 테스트케이스에서는 2, 1, 3, 2 로 들어갔어도 3, 2, 2, 1로 정렬이 됐다.
그러고 priorities 에 있는 것들을 offer로 삽입시켜주었고
queue가 빌 때까지 반복하여, element가 priorities[i]와 같으면
★ poll() 을 활용하여 객체 를 반환해주었다.
같은 숫자 (테스트케이스 2) 라면 객체가 아닌 이상 구분할 수 없기 때문이다.
그렇게 반환하여 location == i 면 answer에 넣어주고 아니면 answer++을 해준 것이다.