[Programmers] 더 맵게 - 힙(Heap)

동민·2021년 3월 11일
import java.util.PriorityQueue;

// 더 맵게 - 힙(Heap)
public class MoreSpicy {
	public int solution(int[] scoville, int K) {
		int answer = 0;

		PriorityQueue<Integer> heap = new PriorityQueue<>(); // Min Heap; new PriorityQueue<>(Collections.reverseOrder()) - Max Heap

		for (int ele : scoville) {
			heap.add(ele);
		}
		
		while (heap.peek() < K) {

			heap.add(heap.poll() + heap.poll() * 2);
			answer++;
			if (heap.size() == 1 && heap.peek() < K) { // 예외 처리 
				return -1;
			}
		}

		return answer;
	}

	public static void main(String[] args) {

		MoreSpicy s = new MoreSpicy();

		int[] scoville = { 1, 2, 3, 9, 10, 12 };

		System.out.println(s.solution(scoville, 7)); // 2

	}
}
PriorityQueue heap = new PriorityQueue<>() - Min Heap
PriorityQueue heap = new PriorityQueue<>(Collections.reverseOrder()) - Max Heap

System.out.print(heap)을 하였을 때 [1, 9, 3, 24, 10, 12] 이면 (최소 힙의 경우)

    1
   / \
   9 3
  /\ /
24 10 12

이와 같은 Tree 구조이며 삽입과 삭제, 조회 연산은 root(min heap의 경우 최소값)에 대해 수행되고 PriorityQueue의 경우 자동으로 heapify 된다.
profile
BE Developer

0개의 댓글