Algorithm
[알고리즘] 우선순위 큐
개발자_미노
2020. 9. 16. 13:58
반응형
우선순위 큐(Priority Queue)
우선순위 큐(Priority Queue)는 들어간 순서에 상관없이 일정한 규칙에 따라 우선순위를 선정하고,
우선순위가 가장 높은 데이터가 가장 먼저 나오게 됩니다.
PriorityQueue<Integer> priorityQueue = new PriorityQueue<>();
priorityQueue.offer(4);
priorityQueue.offer(3);
priorityQueue.offer(2);
priorityQueue.offer(1);
System.our.println(priorityQueue.poll()) // 1 출력
기본적으로 숫자는 낮은 것이 우선순위를 높게 봅니다.
우선순위 변경하기
Java는 기본적으로 오름차순으로 정렬하게 되는데,
만약 다른 오름차순으로 사용하고 싶다면 Compartor 클래스나 Comparable 인터페이스를 이용해야 합니다.
Integer와 같은 숫자는 Collections.reversOrder()를 사용하면 우선순위를 변경할 수 있습니다.
//우선순위를 높은 숫자위주로 변경
PriorityQueue<Integer> priorityQueue = new PriorityQueue<>(Collections.reverseOrder());
priorityQueue.offer(1);
priorityQueue.offer(2);
priorityQueue.offer(3);
priorityQueue.offer(4);
System.out.println(priorityQueue.poll()); // 4 출력
반응형