hayu's 개발 일지

99클럽 코테 스터디 32일차 TIL + 우선순위 큐(PriorityQueue)(2) 본문

자료구조&알고리즘

99클럽 코테 스터디 32일차 TIL + 우선순위 큐(PriorityQueue)(2)

hayu00 2024. 6. 21. 21:15

학습 키워드

- 우선순위 큐(PriorityQueue)

 

공부한 내용

우선순위 큐 선언 방법

// 낮은 수가 우선순위를 가짐
PriorityQueue<Integer> pq = new PriorityQueue<>();

// 높은 수가 우선순위를 가짐
PriorityQueue<Integer> pq = new PriorityQueue<>(Collections.reverseOrder());

//String형 priorityQueue 선언 (우선순위가 낮은 숫자 순)
PriorityQueue<String> priorityQueue = new PriorityQueue<>(); 

//String형 priorityQueue 선언 (우선순위가 높은 숫자 순)
PriorityQueue<String> priorityQueue = new PriorityQueue<>(Collections.reverseOrder());

우선순위 큐 정렬기준 정하기

  • PriorityQueue의 생성하는 단계에서 Comparator 인터페이스를 재정의한다면 원소가 뽑히는 순서(정렬 기준)를 사용자가 원하는대로 재정의할 수 있다.
PriorityQueue<Integer> pq = new PriorityQueue<>(new Comparator<Integer>() {
	@Override
	public int compare(Integer o1, Integer o2) {
		return Integer.compare(o2, o1); // 내림차순 정렬
	}
});
pq.offer(5);
pq.offer(3);
pq.offer(9);
pq.offer(1);

while(!pq.isEmpty()) {
	System.out.println(pq.poll());
}

우선순위 큐 값 추가

priorityQueue.add(1);// priorityQueue 값 1 추가
priorityQueue.add(2);// priorityQueue 값 2 추가
priorityQueue.ofer(3);// priorityQueue 값 3 추가
  • 자바의 우선순위 큐에 값을 추가하고 싶다면 add(value) 또는 offer(value)라는 메서드를 활용한다.
  • add(value) 메서드의 경우 만약 삽입에 성공하면 true를 반환하고, 큐에 여유 공간이 없어 삽입에 실패하면 IllegalStateException을 발생시킨다.
  • 우선순위 큐에 값을 추가한다면 아래 그림과 같은 과정을 통해 즉시 정렬이 됩니다.
  • add() : 우선순위 큐에 원소를 추가. 큐가 꽉 찬 경우 에러 발생
  • offer() : 우선순위 큐에 원소를 추가. 값 추가 실패 시 false를 반환

우선순위 큐 값 삭제

priorityQueue.poll();// priorityQueue에 첫번째 값을 반환하고 제거 비어있다면 null
priorityQueue.remove();// priorityQueue에 첫번째 값 제거
priorityQueue.clear();// priorityQueue에 초기화
  • 우선순위 큐에서 값을 제거하고 싶다면 poll()이나 remove()라는 메서드를 사용하면 된다.
  • 값을 제거할 시 우선순위가 가장 높은 값이 제거된다.
  • pop을 하면 가장 앞쪽에 있는 원소의 값이 아래 그림과 같이 제거된다.
  • poll() : 우선순위 큐에서 첫 번째 값을 반환하고 제거, 비어있으면 null 반환
  • remove() : 우선순위 큐에서 첫 번째 값을 반환하고 제거, 비어있으면 에러 발생
  • isEmpty() : 우선순위 큐에서 첫 번째 값을 반환하고 제거, 비어있으면 에러 발생

우선순위 큐에서 우선순위가 가장 높은 값 출력

PriorityQueue<Integer> priorityQueue = new PriorityQueue<>();//int형 priorityQueue 선언
priorityQueue.offer(2);// priorityQueue에 값 2 추가
priorityQueue.offer(1);// priorityQueue에 값 1 추가
priorityQueue.offer(3);// priorityQueue에 값 3 추가
priorityQueue.peek();// priorityQueue에 첫번째 값 참조 = 1
  • Priority Queue에서 우선순위가 가장 높은 값을 참조하고 싶다면 peek()라는 메서드를 사용하면 된다.
  • 위의 예시에서는 우선순위가 가장 높은 1이 출력한다.

그 외 메서드

  • clear() : 우선순위 큐를 초기화
  • size() : 우선순위 큐에 포함되어 있는 원소의 수를 반환

회고

발생한 문제

- 우선순위 큐의 메서드에 대한 공부가 부족하다는 생각이 들었다.

 

해결 방법

- 우선순위 큐의 메서드를 공부했다. 

 

 

 

참고 자료

- https://cobi-98.tistory.com/45

- https://coding-factory.tistory.com/603