์ฐ์ ์์ ํ
- ์ผ๋ฐ์ ์ธ ํ์ ๋ฌ๋ฆฌ ์ฐ์ ์์๊ฐ ๋์ ์์๊ฐ ๋จผ์ ๋์ค๋ ์๋ฃ๊ตฌ์กฐ
- FIFO๊ฐ ์๋ ์ฐ์ ์์๊ฐ ๋์ ์์๋๋ก ์ฒ๋ฆฌ
์๋ฐ์์ ์ฐ์ ์์ ํ ์ฌ์ฉ๋ฒ
1. ๊ธฐ๋ณธ ์ฌ์ฉ๋ฒ(์ต์ ํ)
- ์ต์ ํ(Min Heap) ๊ตฌ์กฐ
- ๊ฐ์ด ์์ ์์๊ฐ ๋จผ์ ๋์ด
- ์ฃผ์ ๋ฉ์๋
- offer(E item) : ์์ ์ฝ์
- poll() : ๊ฐ์ฅ ์์ ๊ฐ ์ ๊ฑฐ ๋ฐ ๋ฐํ
- peek() : ๊ฐ์ฅ ์์ ๊ฐ ์กฐํ (์ ๊ฑฐ x)
- ๊ตฌํ ๋ฐฉ๋ฒ
import java.util.PriorityQueue;
public class PriorityQueueExample {
public static void main(String[] args) {
// ์ต์ ํ
PriorityQueue<Integer> pq = new PriorityQueue<>();
pq.offer(3);
pq.offer(1);
pq.offer(4);
pq.offer(1);
pq.offer(2);
while (!pq.isEmpty()) {
System.out.println(pq.poll()); // 1 1 2 3 4 (์ค๋ฆ์ฐจ์ ์ถ๋ ฅ)
}
}
}
2. ์ต๋ ํ
- Comparator ์ฌ์ฉํ์ฌ ์ต๋ ํ ๊ตฌํ
๋ฐฉ๋ฒ 1 : Comparator.reverseOrder()
import java.util.PriorityQueue;
import java.util.Collections;
public class MaxHeapExample {
public static void main(String[] args) {
// ์ต๋ ํ
PriorityQueue<Integer> maxHeap = new PriorityQueue<>(Collections.reverseOrder());
maxHeap.offer(3);
maxHeap.offer(1);
maxHeap.offer(4);
maxHeap.offer(1);
maxHeap.offer(2);
while (!maxHeap.isEmpty()) {
System.out.println(maxHeap.poll()); // 4 3 2 1 1 (๋ด๋ฆผ์ฐจ์ ์ถ๋ ฅ)
}
}
}
๋ฐฉ๋ฒ 2 : Comparator ์ง์ ๊ตฌํ
import java.util.PriorityQueue;
import java.util.Comparator;
public class MaxHeapExample {
public static void main(String[] args) {
PriorityQueue<Integer> maxHeap = new PriorityQueue<>( (a, b) -> b - a ); // ๋๋ค์ ์ฌ์ฉ
maxHeap.offer(3);
maxHeap.offer(1);
maxHeap.offer(4);
maxHeap.offer(1);
maxHeap.offer(2);
while (!maxHeap.isEmpty()) {
System.out.println(maxHeap.poll()); // 4 3 2 1 1
}
}
}