728x90
정의)
큐의 구조 FIFO(First In First Out)를 가지면서,
데이터가 들어온 순서대로 데이터가 나가는 것이 아닌 우선순위를 먼저 결정하고 그 우선순위가 높은 데이터가 먼저 나가는 자료구조
import java.util.
Random rand = new Random();
PriorityQueue<Integer> pq = new PriorityQueue<>();
for (int i = 0; i < 10; i++) {
pq.add(rand.nextInt(100));
}
System.out.println(pq);
int temp;
for (int i = 0; i < 10; i++) {
temp = pq.poll();
System.out.print(temp + " ");
}
랜덤으로 숫자를 받아서 그걸 pd라는 우선순위 큐에 넣어 준다
그리고 poll() 을하면 우선순위가 높은거 부터 자동적으로 나온다.
활용)
아래와 같이 활용하여 여러가지에 쓰일 수 있다.
// 낮은 숫자가 우선순위가 높은 방식
PriorityQueue<Integer> pq = new PriorityQueue<>();
// 높은 숫자가 우선순위가 높은 방식
PriorityQueue<Integer> pq = new PriorityQueue<>(Collections.reverseOrder());
// 이중 배열에서 0번째 낮은 숫자가 우선순위가 높은 방식(람다식)
PriorityQueue<int[]> pq = new PriorityQueue<>((o1, o2) -> o1[0] - o2[0]);
// 이중 배열에서 0번째 낮은 숫자가 우선순위가 높은 방식(Comparator)
PriorityQueue<int[]> pq = new PriorityQueue<>(new Comparator<int[]>() {
@Override
public int compare(int[] o1, int[] o2) {
return o1[0] - o2[0];
};
});
728x90
'backjoon > 여러가지' 카테고리의 다른 글
백준 1427 소트인사이드 c언어 (0) | 2023.02.03 |
---|---|
백준 1934 최소공배수 c언어 (0) | 2023.01.29 |
유클리드 호제법 c언어 구현하기 (0) | 2023.01.29 |
qsort함수 (0) | 2023.01.28 |
백준 1037 약수 c언어 (0) | 2023.01.28 |
댓글