본문
더 맵게 #힙(Heap) #level2
프로그래밍/코딩테스트(java) 2021. 1. 19. 18:58
💡 풀이
import java.util.PriorityQueue;
class Solution {
public int solution(int[] scoville, int K) {
PriorityQueue<Integer> pq = new PriorityQueue<>();
for (int i : scoville)
pq.add(i);
// PriorityQueue에 주어진 scoville 점수를 모두 넣은 후, 순차적으로 2번 poll()하여 주어진 식에 맞게 계산한 후 다시 add() 해주며 count를 올려줍니다.
// 이 때 peek() (최소값)이 K를 넘는다면 조건을 만족한 것이므로 break하여 count를 return해 줍니다.
// 추가적으로 size()가 1이면 더이상 계산할 것이 없으므로 바로 -1을 return 해줍니다.
int cnt = 0;
while (true) {
if (pq.peek() >= K)
break;
if (pq.size() == 1)
return -1;
pq.add(pq.poll() + (pq.poll() * 2));
cnt++;
}
return cnt;
}
}
P.S. 우선순위 큐(Priority Queue)
https://server-engineer.tistory.com/811
[Java] 우선순위 큐(Priority Queue)
💡 우선순위 큐(Priority Queue) 일반적인 큐는 제일 먼저 들어간 데이터가 가장 먼저 나오게 되는 자료구조 입니다. 대표적인 예로는 은행업무를 기다리는 손님들의 대기열 입니다. 이런 큐의 특
server-engineer.tistory.com
댓글