๋ณธ๋ฌธ
๋ ๋งต๊ฒ #ํ(Heap) #level2
CS Fundamentals/Algorithm & Logic 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
๋๊ธ