문제풀이/프로그래머스

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

빈둥벤둥 2021. 2. 12. 13:39

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

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

 

코딩테스트 연습 - 이중우선순위큐

 

programmers.co.kr

 

풀이

문제 제목에 힌트가 있듯이 우선순위 큐 2개를 사용하여 구현하였다.

 

하나는 최소힙 구조의 우선순의 큐를 사용하여 저장해주었고, 하나는 Collections.reverseOrder() 메소드를 사용하여 최대힙으로 구현해 주었다. 

 

그리고 연산 기호에 따라 동작을 처리해 주었다.

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
import java.util.*;
 
class Solution {
    public int[] solution(String[] operations) {
        PriorityQueue<Integer> maxq = new PriorityQueue<>(Collections.reverseOrder());
        PriorityQueue<Integer> minq = new PriorityQueue<>();
        
        for(int i = 0; i < operations.length; i++) {
            String[] str = operations[i].split(" ");
            String op = str[0];
            int num = Integer.valueOf(str[1]);
            
            if(op.equals("I")) { //I일때는 num을 삽입
                maxq.add(num);
                minq.add(num);
            } else {
                if(!maxq.isEmpty()) { //삭제하기 전에 큐가 비어있는지 확인.
                    if(num == 1) { //최대값을 삭제한다.
                        int max = maxq.poll();
                        minq.remove(max);
                    } else { //최소값을 삭제한다.
                        int min = minq.poll();
                        maxq.remove(min);
                    }   
                }
            }
        }
        
        if(minq.size() == 0 || maxq.size() == 0) {
            return new int[]{00};
        } else {
            return new int[]{maxq.peek(), minq.peek()};
        }
    }
}
cs