[프로그래머스] LEVEL3 이중우선순위큐 JAVA

Pixel Dophin·2023년 7월 28일
0

프로그래머스

목록 보기
30/55

이중우선순위큐

문제링크

풀이

PriorityQueue 2개를 활용해서 최댓값, 최솟값을 찾기 쉽도록 구현하였다.

코드

import java.util.PriorityQueue;

class Solution {
    public int[] solution(String[] operations) {
        int[] answer = new int[2];
		PriorityQueue<Integer> pqMin = new PriorityQueue<>();
		PriorityQueue<Integer> pqMax = new PriorityQueue<>();

		for (int i = 0; i < operations.length; i++) {
			String[] split = operations[i].split(" ");
			int num = Integer.parseInt(split[1]);

			switch (split[0]) {
			case "I":
				pqMin.offer(num);
				pqMax.offer(-num);
				break;
			case "D":
                if (!pqMin.isEmpty()) {
                    if (num == 1) { // 큐에서 최댓값 삭제
                            pqMin.remove(-1 * pqMax.poll());
                    } else { // 큐에서 최솟값 삭제
                            pqMax.remove(-1 * pqMin.poll());
                    }
                }
				break;
			}
		}

		if (!pqMin.isEmpty()) {
			answer[0] = -1 * pqMax.peek();
			answer[1] = pqMin.peek();
		}
		return answer;
    }
}
profile
안녕 👋 성장하고픈 개발자 💻 입니다

0개의 댓글

관련 채용 정보