
문제 출처
https://www.acmicpc.net/problem/11650

풀이
- 두 객체를 비교할 수 있는지를 묻는 정렬 문제이다.
- Collections.sort()를 이용할 때 new Comparator< T >() {}를 활용할 수 있으면 쉽게 풀 수 있다.
코드
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.StringTokenizer;
public class Main {
public static class Coordinate {
int x;
int y;
public Coordinate(int x, int y) {
this.x = x;
this.y = y;
}
}
public static void main(String[] args) throws IOException {
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer stringTokenizer = new StringTokenizer(bufferedReader.readLine());
int N = Integer.parseInt(stringTokenizer.nextToken());
List<Coordinate> coordinateList = new ArrayList<>();
for (int i = 0; i < N; i++) {
stringTokenizer = new StringTokenizer(bufferedReader.readLine());
coordinateList.add(new Coordinate(Integer.parseInt(stringTokenizer.nextToken()), Integer.parseInt(stringTokenizer.nextToken())));
}
Collections.sort(coordinateList, (o1, o2) -> {
if (o1.x == o2.x) {
return o1.y - o2.y;
} else {
return o1.x - o2.x;
}
});
for (Coordinate coordinate : coordinateList) {
System.out.println(coordinate.x + " " + coordinate.y);
}
}
}
채점 결과
