ezhoon

[인프런] 06-07 좌표 정렬 본문

📖  문제


  • 첫째 줄에 좌표의 개수인 N(3 <=N <=100,000)이 주어집니다.
  • 두 번째 줄부터 N개의 좌표가 x, y 순으로 주어집니다. x, y값은 양수만 입력됩니다.
    • N개의 평면상의 좌표(x, y)가 주어지면 모든 좌표를 오름차순으로 정렬하는 프로그램을 작성하세요.
    • 정렬 기준은 먼저 x값의 의해서 정렬하고, x값이 같을 경우 y값에 의해 정렬합니다.

출력 예시

⚠️  주의사항


  • 모든 좌표를 오름차순으로 정렬
  • x값에 의해서 먼저 정렬하지만 x값이 같은 경우 y값에 의해 정렬

 

✍️  이해


/**
 * 1. N 입력
 * 2. x 값에 의해서 정렬이지만 x값이 같은 경우 y값 정렬
 *  2-1. Comparable 사용
 * 3. Collections.sort 이용해서 정렬
 * 4. 좌표 문제 나올 때마다 사용하게 되므로 구조 자체를 외워두기
 */

 

✏️  풀이


import java.util.ArrayList;
import java.util.Collections;
import java.util.Scanner;

public class Main {

    static class Point implements Comparable<Point>{

        // 좌표 시작 -> 외워버리기
        public int x, y;

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

        @Override
        public int compareTo(Point o){
            if (this.x == o.x) {
                return this.y - o.y; // 내림차순이면 순서만 바꿔주기
            } else {
                return this.x - o.x;
            }
        }
        // 좌표 끝
    }

    public static void main(String[] args) {
        Main T = new Main();

        Scanner sc = new Scanner(System.in);
        int N = sc.nextInt();

        ArrayList<Point> arr = new ArrayList<>();

        for (int i = 0; i < N; i++) {
            int x = sc.nextInt();
            int y = sc.nextInt();

            arr.add(new Point(x, y));
        }
        Collections.sort(arr);
        for (Point point : arr) System.out.println(point.x + " " + point.y);
    }
}

 

Comments