알고리즘

[백준 11286 silver 1] 절댓값 힙 JAVA

나는 나야 2024. 5. 25. 07:38

매우 직관적으로 우선순위 큐를 사용하면 풀 수 있는 문제였습니다. 하지만 절댓값을 기준으로 가장 작은 값을 가져오는 것이기 때문에 정렬이 필요했죠.

그래서 저는 중첩 클래스를 만들어 Comparable을 구현했고, 이를 통해 풀어낼 수 있었습니다.

 

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Comparator;
import java.util.PriorityQueue;

public class Main{
    public static class ABS implements Comparable<ABS>{
        int x;
        int absx;

        public ABS(int x, int absx) {
            this.x = x;
            this.absx = absx;
        }

        @Override
        public int compareTo(ABS o) {
            if(this.absx != o.absx) {
                return Integer.compare(this.absx, o.absx);
            }
            return Integer.compare(this.x, o.x);
        }
    }
    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        int n = Integer.parseInt(br.readLine());

        PriorityQueue<ABS> pq = new PriorityQueue<>();

        for (int i = 0; i < n; i++) {
            int param = Integer.parseInt(br.readLine());

            if(param != 0) {
                pq.add(new ABS(param, Math.abs(param)));
            }
            else {
                if(pq.isEmpty()){
                    System.out.println(0);
                    continue;
                }
                ABS value = pq.poll();
                System.out.println(value.x);
            }
        }
    }
}

 

이런식으로 문제를 풀어 공간복잡도가 높았고, 또한 내부 실행에서 시간복잡도는 크지 않지만 참조객체를 생성하고 빼는 과정에서 많은 시간이 들었을 것 같습니다.

 

그래서 찾아보니 중첩 클래스를 만들지 않고 구현해놓은

코드가 있었습니다.

 

  PriorityQueue<Integer> pq = new PriorityQueue<>((o1, o2) -> {
            int absCompare = Math.abs(o1) - Math.abs(o2);
            if (absCompare == 0) return o1 - o2;
            else return absCompare;
        });

이런 식으로 절댓값을 통해 비교 후 같다면 값이 -인지 + 인지 판단해서 정렬하는 것이죠.

 

또 하나 배워가는 것 같습니다. 다음에는 무작정 클래스를 만들지 말고 다른 방법이 있나 좀 더 생각해봐야겠습니다.