[프로그래머스] 이중우선순위큐 (java)

HaYeong Jang·2021년 4월 5일
0
post-thumbnail

🔗 문제링크

https://programmers.co.kr/learn/courses/30/lessons/42628

👩🏻‍💻 코드

import java.util.*;

class Solution {
    public int[] solution(String[] operations) {
        PriorityQueue<Integer> pq = new PriorityQueue<>();  // 오름차순
        PriorityQueue<Integer> reverse_pq = new PriorityQueue<>(Comparator.reverseOrder()); // 내림차순
        int[] answer = new int[2];

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

            if (oper.equals("I")) {
                pq.add(num);
                reverse_pq.add(num);
            } else if (oper.equals("D")) {
                if (num == 1) { // 최댓값 삭제
                    Integer max = reverse_pq.poll();
                    pq.remove(max);
                } else {    // 최솟값 삭제
                    Integer min = pq.poll();
                    reverse_pq.remove(min);
                }
            }
        }

        if (!pq.isEmpty()) {
            answer[0] = reverse_pq.peek();
            answer[1] = pq.peek();
        }

        return answer;
    }
}

📝 정리

  1. Priority Queue를 오름차순, 내림차순 하나씩 만든다.
  2. I 명령에는 두 큐에 추가해 준다.
  3. D 명령에는 최댓값은 내림차순 큐에서, 최솟값은 오름차순 큐에서 poll 한다.
    두 큐에서 삭제해 준다.
  4. 큐가 비어있지 않을 경우 [최댓값, 최솟값]을 리턴한다.
profile
기억하기 위해 기록하는 개발로그👣

0개의 댓글