PriorityQueue
- PriorityQueue는 우선순위 기반으로 요소를 정렬하여 저장하는 자료구조입니다.
- 일반적인 Queue(FIFO)와는 다르게, 항상 우선순위가 가장 높은 요소가 먼저 나오는 특징을 가집니다.
- Java에서는 내부적으로 힙(Heap) 자료구조를 사용하여 구현되어 있습니다.
주요 특징
자료구조 |
최소 힙(Min-Heap) 기반 (기본적으로 가장 작은 값이 우선) |
크기 조정 |
필요 시 배열을 2배로 확장 |
삽입 속도 |
O(log n) (힙 특성 유지) |
삭제 속도 |
O(log n) (힙 재정렬) |
탐색 속도 (peek) |
O(1) (최상단 요소 바로 접근) |
중복 허용 |
O (같은 값을 여러 번 저장 가능) |
null 허용 |
❌ (null 저장 시 NullPointerException) |
대표 메서드
package structure.priorityqueue;
import java.util.PriorityQueue;
public class PriorityQueueClass {
private final PriorityQueue<Integer> priorityQueue;
public PriorityQueueClass(PriorityQueue<Integer> priorityQueue) {
this.priorityQueue = priorityQueue;
}
// 우선순위 큐에 값을 추가합니다.
// 시간 복잡도: O(log n)
// 예외 발생: NullPointerException - priorityQueue가 null이거나 값이 null인 경우
public PriorityQueue<Integer> offer(int value) {
this.priorityQueue.offer(value);
return this.priorityQueue;
}
// 우선순위가 가장 높은(가장 작은) 요소를 제거하고 반환합니다.
// 시간 복잡도: O(log n)
// 예외 발생: NullPointerException - priorityQueue가 null인 경우
public Integer poll() {
return this.priorityQueue.poll();
}
// 우선순위가 가장 높은(가장 작은) 요소를 반환합니다(제거하지 않음).
// 시간 복잡도: O(1)
// 예외 발생: NullPointerException - priorityQueue가 null인 경우
public Integer peek() {
return this.priorityQueue.peek();
}
// 큐의 모든 요소를 제거합니다.
// 시간 복잡도: O(1)
// 예외 발생: NullPointerException - priorityQueue가 null인 경우
public void clear() {
this.priorityQueue.clear();
}
// 큐가 비어 있는지 확인합니다.
// 시간 복잡도: O(1)
// 예외 발생: NullPointerException - priorityQueue가 null인 경우
public boolean isEmpty() {
return this.priorityQueue.isEmpty();
}
// 큐의 요소 개수를 반환합니다.
// 시간 복잡도: O(1)
// 예외 발생: NullPointerException - priorityQueue가 null인 경우
public int size() {
return this.priorityQueue.size();
}
// 큐에 지정된 값이 포함되어 있는지 확인합니다.
// 시간 복잡도: O(n) (전체를 탐색)
// 예외 발생: NullPointerException - priorityQueue가 null인 경우
public boolean contains(int value) {
return this.priorityQueue.contains(value);
}
}