문제를 풀고 다른 사람들의 코드로 더 적합한 방법이 있나 찾아보았는데, 다들 compare을 오버라이딩해서 문제를 풀었다는 사실을 알 수 있었다.
틀린 방법은 아니지만 나는 직관적으로 이해하기 어려웠고, 내가 푼 방법이 적혀있지 않은 것 같아서 내 코드를 공유해보고자 한다.
import java.io.*;
import java.util.ArrayList;
import java.util.List;
import java.util.PriorityQueue;
// 11286
public class Main {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));
int n = Integer.parseInt(br.readLine());
List<Integer> arr = new ArrayList<>();
PriorityQueue<Integer> pq = new PriorityQueue<>();
while(n-->0){
int x = Integer.parseInt(br.readLine());
int abs = Math.abs(x);
if(x==0){ // remove
if(pq.isEmpty()) bw.write(0 + "\n");
else {
int out = pq.poll();
if(arr.contains(out)){
bw.write("-" + out + "\n");
arr.remove(Integer.valueOf(out));
}else{
bw.write(out + "\n");
}
}
}else{ // insert
pq.add(abs);
if(x<0){
arr.add(abs);
}
}
}
bw.flush();
bw.close();
br.close();
}
}
특별한 점은 추가적인 list가 존재한다는 것이다.
이 list는 음의 정수를 기록하기 위해 만들었다.
우선 priority queue의 비교값은 입력값의 절댓값이기에 Math.abs()를 사용해서 pq를 채워준다.
문제 조건에서
"절댓값이 가장 작은 값이 여러개일 때는, 가장 작은 수를 출력하고, 그 값을 배열에서 제거한다."
즉 만약 -1과 1이 있다면 -1을 우선순위로 두어야한다는 뜻이다.
그래서 pq에 abs된 절댓값을 넣고, x가 음수라면 list에도 추가로 절댓값을 넣는다.
출력시(즉 x==0일 때) 추가적인 if문으로 리스트에 pq에서 remove되는 요소가 list에 있다면 그 값은 음수로 출력하도록 코드를 작성하였다.
중복 출력을 방지하기 위해 리스트에서 사용하면 그 값을 제거해주는 로직도 있어야 한다.