Java에서 Heap은 PriorityQueue를 활용하여 쉽게 구현할 수 있다.
최대 힙은 root에 최댓값이 최소 힙은 root 최솟값이 저장되어 있는 이진 트리라고 생각하면 된다.
기본적으로 Java에서 PriorityQueue는 최소힙으로 구현되어 있다.
// 최대 힙
PriorityQueue<Integer> maxHeap = new PriorityQueue<>(Collections.reverseOrder());
// 최소 힙
PriorityQueue<Integer> minHeap = new PriorityQueue<>();
Collections.reverseOrder()을 이용하여 최대 힙으로 구현 가능하다.
[백준 11279]
간단한 최대 힙 구현 문제이다.
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.*;
public class Main {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int n = Integer.parseInt(br.readLine());
PriorityQueue<Integer> heap = new PriorityQueue<>(Collections.reverseOrder());
for (int i=0; i<n; i++) {
int x = Integer.parseInt(br.readLine());
if (x == 0) {
if(heap.isEmpty()) System.out.println(0);
else System.out.println(heap.poll());
}
else{
heap.add(x);
}
}
}
}
이 외에도 PrioritiyQueue 정렬을 커스텀할 수 있다.
https://coding-tomorrow.tistory.com/27
[Java / 알고리즘] 우선순위 큐 (Priority Queue)
1. 우선순위 큐 (Priority Queue) 란 우선순위 큐란 임의의 데이터 항목이 삽입되고, 일정한 순서에 의해 삭제되는 데이터 구조이다. 즉, 들어간 데이터의 순서에 상관없이 우선순위가 높은 데이터가
coding-tomorrow.tistory.com
'개발 언어 > JAVA' 카테고리의 다른 글
| [JAVA/알고리즘] TreeMap 트리 맵 (백준 7662) (0) | 2025.04.09 |
|---|---|
| [JAVA/알고리즘] 백준 2579 계단 오르기 (DP) (0) | 2025.03.17 |
| [JAVA/알고리즘] 너비 우선 탐색 BFS (백준 14940) (0) | 2025.03.06 |
| [JAVA/알고리즘] HashSet clear()와 removeAll() 메모리 (백준 1697) (0) | 2025.03.05 |
| [JAVA/알고리즘] 분할 정복 알고리즘 Divide and conquer (백준 2630) (0) | 2025.03.03 |