https://programmers.co.kr/learn/courses/30/lessons/42628
import java.util.*;
class Solution {
public int[] solution(String[] operations) {
PriorityQueue<Integer> minq = new PriorityQueue<>();
PriorityQueue<Integer> maxq = new PriorityQueue<>(Collections.reverseOrder());
for (String oper : operations) {
StringTokenizer st = new StringTokenizer(oper);
String op = st.nextToken();
int value = Integer.parseInt(st.nextToken());
if (op.equals("I")) {
minq.offer(value);
maxq.offer(value);
}
else if (!maxq.isEmpty()) {
if (value == 1) {
int max = maxq.poll();
minq.remove(max);
}
else {
int min = minq.poll();
maxq.remove(min);
}
}
}
if (maxq.isEmpty()) {
int[] answer = {0, 0};
return answer;
}
else {
int[] answer = {maxq.peek(), minq.peek()};
return answer;
}
}
}
이중우선순위큐를 구현하기위해 minq
와 maxq
를 이용해 구현하였다. 명령어가 D
일때는 큐가 비었는지부터 체크후 각 큐에 맞는 값을 뺀후 나머지 큐는 remove
메소드를 통해 삭제해준다. answer
를 출력할때는 큐가 비었을때는 [0, 0]
을 출력하고 아닐때는 maxq
와 minq
의 루트값을 출력하면 된다.