99클럽 코테 스터디 TIL - 이중우선순위큐

혀니·2024년 4월 4일

코딩 TIL

목록 보기
6/28

프로그래머스 Lv3 이중우선순위큐

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

처음으로는 LV3 이중우선순위 큐를 풀었다.

Lv3이길래 어려운줄 알았으나
문제 이름 답게 PriorityQueue를 사용하면 쉽게 풀 수 있다.

우선순위 큐에서 최솟값을 우선순위로 하는 큐와 최댓값을 우선순위로 하는 큐를 2개 만들어 최솟값과 최댓값을 쉽게 삭제, 리턴할 수 있었다.

첫번째 문제는 우선순위 큐를 2개 만들면 된다는 것만 알면 쉽게 풀 수 있는 문제인 것 같았다 :D
근데 프로그래머스에서는 자동완성이 안되다보니 내가 함수를 확실히 모르고 있다는 것을 느끼게 되는 것 같다.ㅠㅠ

import java.util.*;

class Solution {
    public int[] solution(String[] operations) {
        PriorityQueue <Integer> priorityQueue1 = new PriorityQueue<>(); //작은 순
        PriorityQueue <Integer> priorityQueue2 = new PriorityQueue<>(Collections.reverseOrder()); // 큰 순

        String str;
        int input=0, max = 0, min = 0;
        for(int i=0;i<operations.length;i++){
            str = operations[i].split(" ")[0];
            input = Integer.parseInt(operations[i].split(" ")[1]);

            if(str.equals("I"))
            {
                priorityQueue1.add(input);
                priorityQueue2.add(input);
            } else if(str.equals("D") && !priorityQueue1.isEmpty()){
                if(input == 1){
                    //큐에서 최댓값 삭제
                    max = priorityQueue2.peek();
                    priorityQueue2.remove();
                    priorityQueue1.remove(max);
                } else if(input == -1){
                    //큐에서 최솟값 삭제
                    min = priorityQueue1.peek();
                    priorityQueue1.remove();
                    priorityQueue2.remove(min);
                }
            }
        }
        int[] answer = new int[2];
        if(priorityQueue1.isEmpty() && priorityQueue2.isEmpty()){
            answer[0] = 0;
            answer[1] = 0;
        } else{
            answer[0] = priorityQueue2.peek();
            answer[1] = priorityQueue1.peek();
        }
        return answer;
    }
    
}

0개의 댓글