[프로그래머스] 코딩테스트 연습 - 힙(Heap) Level 3 이중우선순위 큐

uoahy·2021년 9월 21일
0

Solution.java

import java.util.*;

class Solution {
    public int[] solution(String[] operations) {
        int[] answer = {};
        
        TreeMap<Integer, Integer> tm = new TreeMap<>();
        
        for (String op : operations) {
            String[] tmp = op.split(" ");
            int num = Integer.parseInt(tmp[1]);
            
            if (tmp[0].equals("I")) {
                tm.put(num, tm.getOrDefault(num, 0) + 1);
            }
            else {
                if (!tm.isEmpty()) {
                    if (num == 1)  {
                        int max = tm.lastKey();
                        if (tm.get(max) > 1) tm.put(max, tm.get(max) - 1);
                        else tm.remove(max);
                    }
                    else {
                        int min = tm.firstKey();
                        if (tm.get(min) > 1) tm.put(min, tm.get(min) - 1);
                        else tm.remove(min);
                    }
                }
            }
        }
        
        answer = new int[2];
        
        if (!tm.isEmpty()) {
            answer[0] = tm.lastKey();
            answer[1] = tm.firstKey();
        }
        
        return answer;
    }
}

힙 카테고리의 문제였지만 우선순위 큐를 사용하는것보다 트리맵이 좋아보여 트리맵을 사용하여 풀었다.

다른 사람의 풀이를 보고 자바 우선순위 큐엔 임의의 값을 삭제할 수 있는 remove 메소드가 있다는걸 알게되었다.

출처: 프로그래머스 코딩 테스트 연습, https://programmers.co.kr/learn/challenges

0개의 댓글