์šฐ์„ ์ˆœ์œ„ ํ

  • ์ผ๋ฐ˜์ ์ธ ํ์™€ ๋‹ฌ๋ฆฌ ์šฐ์„ ์ˆœ์œ„๊ฐ€ ๋†’์€ ์š”์†Œ๊ฐ€ ๋จผ์ € ๋‚˜์˜ค๋Š” ์ž๋ฃŒ๊ตฌ์กฐ
  • FIFO๊ฐ€ ์•„๋‹Œ ์šฐ์„ ์ˆœ์œ„๊ฐ€ ๋†’์€ ์ˆœ์„œ๋Œ€๋กœ ์ฒ˜๋ฆฌ

์ž๋ฐ”์—์„œ ์šฐ์„ ์ˆœ์œ„ ํ ์‚ฌ์šฉ๋ฒ•

1. ๊ธฐ๋ณธ ์‚ฌ์šฉ๋ฒ•(์ตœ์†Œ ํž™)

  • ์ตœ์†Œ ํž™(Min Heap) ๊ตฌ์กฐ
  • ๊ฐ’์ด ์ž‘์€ ์š”์†Œ๊ฐ€ ๋จผ์ € ๋‚˜์˜ด
  • ์ฃผ์š” ๋ฉ”์„œ๋“œ
    • offer(E item) : ์š”์†Œ ์‚ฝ์ž…
    • poll() : ๊ฐ€์žฅ ์ž‘์€ ๊ฐ’ ์ œ๊ฑฐ ๋ฐ ๋ฐ˜ํ™˜
    • peek() : ๊ฐ€์žฅ ์ž‘์€ ๊ฐ’ ์กฐํšŒ (์ œ๊ฑฐ x)
  • ๊ตฌํ˜„ ๋ฐฉ๋ฒ•
    • PriorityQueue ํด๋ž˜์Šค
import java.util.PriorityQueue;
 
public class PriorityQueueExample {
    public static void main(String[] args) {
	     // ์ตœ์†Œ ํž™
        PriorityQueue<Integer> pq = new PriorityQueue<>();
 
        pq.offer(3);
        pq.offer(1);
        pq.offer(4);
        pq.offer(1);
        pq.offer(2);
 
        while (!pq.isEmpty()) {
            System.out.println(pq.poll()); // 1 1 2 3 4 (์˜ค๋ฆ„์ฐจ์ˆœ ์ถœ๋ ฅ)
        }
    }
}

2. ์ตœ๋Œ€ ํž™

  • Comparator ์‚ฌ์šฉํ•˜์—ฌ ์ตœ๋Œ€ ํž™ ๊ตฌํ˜„
๋ฐฉ๋ฒ• 1 : Comparator.reverseOrder()
import java.util.PriorityQueue;
import java.util.Collections;
 
public class MaxHeapExample {
    public static void main(String[] args) {
        // ์ตœ๋Œ€ ํž™
        PriorityQueue<Integer> maxHeap = new PriorityQueue<>(Collections.reverseOrder()); 
        
        maxHeap.offer(3);
        maxHeap.offer(1);
        maxHeap.offer(4);
        maxHeap.offer(1);
        maxHeap.offer(2);
 
        while (!maxHeap.isEmpty()) {
            System.out.println(maxHeap.poll()); // 4 3 2 1 1 (๋‚ด๋ฆผ์ฐจ์ˆœ ์ถœ๋ ฅ)
        }
    }
}
๋ฐฉ๋ฒ• 2 : Comparator ์ง์ ‘ ๊ตฌํ˜„
import java.util.PriorityQueue;
import java.util.Comparator;
 
public class MaxHeapExample {
    public static void main(String[] args) {
        PriorityQueue<Integer> maxHeap = new PriorityQueue<>( (a, b) -> b - a ); // ๋žŒ๋‹ค์‹ ์‚ฌ์šฉ
 
        maxHeap.offer(3);
        maxHeap.offer(1);
        maxHeap.offer(4);
        maxHeap.offer(1);
        maxHeap.offer(2);
 
        while (!maxHeap.isEmpty()) {
            System.out.println(maxHeap.poll()); // 4 3 2 1 1
        }
    }
}