PriorityQueue

CHEESE·2021년 11월 17일
0

👑 PriorityQueue

java.util.PriorityQueue
FIFO 구조를 가진 Queue에 우선순위가 포함된 자료구조
우선순위를 먼저 결정하고 우선순위가 높은 엘리먼트가 먼저 나감
데이터를 삽입할 때 우선순위를 기준으로 최대 힙 또는 최소 힙을 구성함

🎨 특징

  1. 우선순위 큐에 들어가는 원소는 비교가 가능한 기준이 있어야 한다.
  2. 내부 요소는 힙으로 구성된다.
  3. 이진 트리 구조로 구성된다.
  4. 시간 복잡도는 O(NlogN)

📢 선언하기

import java.util.Collections;
import java.util.PriorityQueue;

public class PriorityQueueExam {

	public static void main(String[] args) {
		// 우선순위 낮은 순
		PriorityQueue<Integer> q1 = new PriorityQueue<>();
		// 우선순위 높은 순
		PriorityQueue<Integer> q2 = new PriorityQueue<>(Collections.reverseOrder());
	}
}

🔎 값 추가하기

	// 값 추가
	q1.add(1);
	q1.offer(2);
		
	q2.add(1);
	q2.offer(2);

offer()

정상적으로 추가된 경우 true, 아닌(큐가 가득찬) 경우 false를 반환

add()

추가할 수 없는 경우 IllegalStateException을 발생

🔎 값 꺼내기

	System.out.println("*** q1 poll");
	System.out.println(q1.poll());	// 1
	System.out.println(q1.poll());	// 2
	System.out.println("*** q2 poll");
	System.out.println(q2.poll());	// 2
	System.out.println(q2.poll());	// 1
		
	System.out.println("*** q1 peek");
	System.out.println(q1.peek());	// 1
	System.out.println(q1.peek());	// 1
	System.out.println("*** q2 peek");
	System.out.println(q2.peek());	// 2
	System.out.println(q2.peek());	// 2

poll()

우선순위가 가장 높은 값을 반환하고 우선순위 큐에서 제거

peek()

우선순위가 가장 높은 값을 반환 (참조의 역할)

0개의 댓글