🥞 BE
home

42628_이중우선순위큐

담당자
완료 여부
Solved
요약
날짜
2024/08/06
태그
난이도
Lv3
출처
프로그래머스

코드

import java.util.Collections; import java.util.PriorityQueue; import java.util.Queue; class Solution { public int[] solution(String[] operations) { Queue<Integer> minHeap = new PriorityQueue<>(); Queue<Integer> maxHeap = new PriorityQueue<>(Collections.reverseOrder()); for (String operation : operations) { // 띄어쓰기를 기준으로 명령과 값 분리 String[] parts = operation.split(" "); String command = parts[0]; int number = Integer.parseInt(parts[1]); if (command.equals("I")) { // 삽입 연산 minHeap.add(number); maxHeap.add(number); } else if (command.equals("D")) { // 삭제 연산 if (number == 1 && !maxHeap.isEmpty()) { // 최대값 삭제 int maxValue = maxHeap.poll(); minHeap.remove(maxValue); } else if (number == -1 && !minHeap.isEmpty()) { // 최솟값 삭제 int minValue = minHeap.poll(); maxHeap.remove(minValue); } } } // 큐가 비어있으면 [0, 0]을 반환 if (minHeap.isEmpty()) { return new int[]{0, 0}; } else { // 아니라면 max, min 힙을 반환 return new int[]{maxHeap.peek(), minHeap.peek()}; } } }
Java
복사

문제 해결 아이디어

최대 힙과 최소 힙을 활용해 연산자에 맞는 로직을 구성하면 된다.