티스토리 뷰


1. Java 구현

            
import java.io.*;
import java.util.*;

public class Main {

   public class Pair implements Comparable {

       private int x;
       private int y;

       public Pair(int x, int y) {
           this.x = x;
           this.y = y;
       }

       @Override
       public int compareTo(Pair o) {
           if(this.y > o.y) {
               return 1;
           } else if(this.y == o.y && this.x > o.x) {
               return 1;
           } else if(this.y == o.y && this.x < o.x) {
               return -1;
           }  else if(this.y < o.y) {
               return -1;
           }
           return 0;
       }
   }

    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));
        StringBuilder sb = new StringBuilder();

        List list = new ArrayList<>();
        int n = Integer.parseInt(br.readLine());
        for (int i = 0; i < n; i++) {
            StringTokenizer st = new StringTokenizer(br.readLine());
            list.add(new Main().new Pair(Integer.parseInt(st.nextToken())
                    , Integer.parseInt(st.nextToken())));
        }

        Collections.sort(list);

        for(Pair pair : list) {
            sb.append(pair.x).append(" ").append(pair.y).append("\n");
        }

        bw.write(sb.toString());
        bw.close();
    }

}


2. 코드설명

 이 문제는 좌표 y값을 우선적으로 정렬하고, y값이 동등한 좌표에 대해서는 x값으로 정렬하여 순차적으로 출력하는 문제이다.

 결국은 하나의 기준이 아닌, 두개의 기준으로 정렬을 해야하는 문제이다. 그래서 정렬기준을 재정의 해야할 필요가 있었다.

 Comparable 인터페이스의 compareTo 메소드를 오버라이드하여 재정의했다. 자바에서는 이 방식으로 풀이가 가능한데, 다른 언어에서는 어떻게 구현했는지 궁금하다.


3. Pain Point

 Comparable 인터페이스를 몰랐다면 쉽게 풀수 없을 것 같은 문제였다. (내 기준)


공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
«   2024/05   »
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
글 보관함