알고리즘/프로그래머스

이중우선순위큐

베리영young 2024. 12. 18. 21:12

사용 알고리즘: 우선순위 큐

사용 언어: java

 

// * 우선순위 큐는 '값으로 접근'이 가능함 (권장되지는 않음)
import java.util.*;

class Solution {
    Queue<Integer> maxQueue = new PriorityQueue<>((a, b) -> b - a);
    Queue<Integer> minQueue = new PriorityQueue<>();
    
    public int[] solution(String[] operations) {
        int[] answer = new int[2];
        for(int i=0; i<operations.length; i++) {
            String[] op = operations[i].split(" ");
            if(op[0].equals("I")) {
                maxQueue.add(Integer.parseInt(op[1]));
                minQueue.add(Integer.parseInt(op[1]));
            }
            else {
                if(maxQueue.isEmpty() || minQueue.isEmpty())
                    continue;
                if(op[1].equals("-1")) {
                    int min = minQueue.poll();
                    maxQueue.remove(min);
                }
                else {
                    int max = maxQueue.poll();
                    minQueue.remove(max);
                }
            }
        }
        
        if(!maxQueue.isEmpty()) answer[0] = maxQueue.poll();
        if(!minQueue.isEmpty()) answer[1] = minQueue.poll();
        return answer;
    }
}

 

우선순위 큐는 값으로 접근 가능 (추천x)

이렇게도 접근 가능하구나~하고 실전에서는 공식 문서 확인하면 될 듯