본문 바로가기

Programming/Java

[Java] x,y 좌표 정렬 하기

설명

N개의 평면상의 좌표(x, y)가 주어지면 모든 좌표를 오름차순으로 정렬하는 프로그램을 작성하세요.

정렬기준은 먼저 x값의 의해서 정렬하고, x값이 같을 경우 y값에 의해 정렬합니다.

입력

첫째 줄에 좌표의 개수인 N(3<=N<=100,000)이 주어집니다.

두 번째 줄부터 N개의 좌표가 x, y 순으로 주어집니다. x, y값은 양수만 입력됩니다.

출력

N개의 좌표를 정렬하여 출력하세요.

예시 입력 1 

5
2 7
1 3
1 2
2 5
3 6

예시 출력 1

1 2
1 3
2 5
2 7
3 6

문제풀이

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


class Point implements Comparable<Point> {
public int x;
public int y;

public 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;
// 내림차순
/*if (this.x == o.x) return o.y - this.y;
else return o.x - this.x;*/
}
}


public class Main27 {


public List<Point> solution(List<Point> points) {
Collections.sort(points);
return points;
}

public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
Main27 T = new Main27();
int n = sc.nextInt();
List<Point> arr = new ArrayList<>();

for (int j = 0; j < n; j++) {
int x = sc.nextInt();
int y = sc.nextInt();
arr.add(new Point(x, y));
}

for (Point o : T.solution(arr)) {
System.out.println(o.x + " " + o.y);
}
}
}

Point 클래스를 선언하고 Comparable 인터페이스를 상속받도록 처리할 것

 

x좌표가 같으면 y좌표를 오름차순으로 정렬하도록 처리

728x90