[Programmers] 이중우선순위큐 - 힙(Heap)

동민·2021년 3월 11일
import java.util.Collections;
import java.util.PriorityQueue;

// 이중우선순위큐 - 힙(Heap)
public class DoublePriorityQueue {
	public int[] solution(String[] operations) {
		int[] answer = new int[2];

		PriorityQueue<Integer> heap = new PriorityQueue<>(Collections.reverseOrder());

		for (String ele : operations) {
			if (ele.split(" ")[0].equals("I")) {
				heap.offer(Integer.parseInt(ele.split(" ")[1]));
			} else {
				if (ele.split(" ")[1].equals("-1")) {
					heap = removeMin(heap);
				} else {
					heap.poll();
				}
			}
		}

		if (heap.size() >= 2) {
			answer[0] = heap.poll();
			answer[1] = retMin(heap);
		} else if (heap.size() >= 1) {
			answer[0] = heap.poll();
			answer[1] = 0;
		}

		return answer;
	}

	private PriorityQueue<Integer> removeMin(PriorityQueue<Integer> heap) {
		PriorityQueue<Integer> minHeap = new PriorityQueue<>();
		while (!heap.isEmpty()) {
			minHeap.offer(heap.poll());
		}
		minHeap.poll();
		while (!minHeap.isEmpty()) {
			heap.offer(minHeap.poll());
		}
		return heap;
	}

	private int retMin(PriorityQueue<Integer> heap) {
		PriorityQueue<Integer> minHeap = new PriorityQueue<>();
		while (!heap.isEmpty()) {
			minHeap.offer(heap.poll());
		}
		return minHeap.poll();
	}
}
profile
BE Developer

0개의 댓글