๋ณธ๋ฌธ

๋” ๋งต๊ฒŒ #ํž™(Heap) #level2

https://programmers.co.kr/learn/courses/30/lessons/42626

 

๐Ÿ’ก ํ’€์ด

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

 

 

 

๊ณต์œ 

๋Œ“๊ธ€

Cloud & AI Engineering | ์ž„์Šนํ•œ

design by tokiidesu. powerd by AXZ.