public static int solution(int[] scoville, int K) {
int answer = 0;
PriorityQueue<Integer> pq = new PriorityQueue<>();
//요건 내림차순
//PriorityQueue<Integer> pq = new PriorityQueue<>(Collections.reverseOrder());
for (int s : scoville) {
pq.add(s);
}
int cnt = 1;
while (!pq.isEmpty()) {
int first_val = pq.poll();
if(pq.isEmpty()) {
cnt = -1;
break;
}
int second_val = pq.poll();
int sum = first_val + (second_val * 2);
pq.add(sum);
System.out.println(pq);
if (pq.peek() >= K) {
break;
}
cnt++;
}
answer = cnt;
return answer;
}
내가 우선순위 큐의 특징에 대해 조금만 더 잘 알았다면 금방 풀 수 있었을 문제..! 비록 시간을 좀 잡아먹긴 했지만 통과했고, 공부했다 !!!
우선순위 큐는 큐와 동일한 메소드가 사용되지만 (add, offer, poll 등) 다른 점이 있다면 큐에 값 추가 시 즉시 정렬되어 들어간다. 우선순위 큐는 다른 포스트에서 좀 더 자세하게 다뤄야겠다.
코드리뷰랄게 없지만 나는 우선순위 큐에 원소를 다 담아 오름차순 정렬시킨 후 계산된 스코빌지수를 계속 추가하여 기준이 될 값과 비교하였다. 처음엔 heapSort라는 함수를 따로 만들고 반복문을 돌려 정렬시킨 큐를 계속 리턴해주는 방식으로 짰었는데 효율성에서 다 탈락했다.. 알고리즘을 좀 더 공부해야겠다.