[java] 자바 힙에서 최소/최대값 삭제하기

자바에서는 PriorityQueue를 사용하여 힙(Heap)을 구현할 수 있습니다. 힙은 데이터를 저장할 때 최솟값 또는 최댓값에 상수 시간(Ο(1))으로 접근할 수 있는 자료구조입니다. 이 글에서는 PriorityQueue를 사용하여 힙에서 최소값과 최대값을 삭제하는 방법에 대해 알아보겠습니다.

최소값 삭제하기

import java.util.PriorityQueue;

public class MinHeapExample {
    public static void main(String[] args) {
        PriorityQueue<Integer> minHeap = new PriorityQueue<>();
        minHeap.add(5);
        minHeap.add(3);
        minHeap.add(7);
        System.out.println("Min Heap: " + minHeap); 
        minHeap.poll(); // Removes the minimum element from the heap
        System.out.println("Min Heap after deletion: " + minHeap); 
    }
}

위의 예제에서는 PriorityQueue를 사용하여 최소 힙을 구현하고, poll() 메서드를 사용하여 최솟값을 삭제하고 나머지 값을 출력하는 방법을 보여줍니다.

최대값 삭제하기

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

public class MaxHeapExample {
    public static void main(String[] args) {
        PriorityQueue<Integer> maxHeap = new PriorityQueue<>(Collections.reverseOrder());
        maxHeap.add(5);
        maxHeap.add(3);
        maxHeap.add(7);
        System.out.println("Max Heap: " + maxHeap); 
        maxHeap.poll(); // Removes the maximum element from the heap
        System.out.println("Max Heap after deletion: " + maxHeap); 
    }
}

위의 예제에서는 PriorityQueue를 사용하여 최대 힙을 구현하고, Collections.reverseOrder()를 사용하여 역순으로 정렬하여 최대값을 삭제하고 나머지 값을 출력하는 방법을 보여줍니다.

결론

이렇게 하면 자바에서 힙의 최소값과 최대값을 삭제할 수 있습니다. 힙은 우선순위 큐, 작업 스케줄링, 이벤트 시뮬레이션 등 다양한 애플리케이션에 유용하게 사용될 수 있는 자료구조 중 하나입니다.

참고 자료