문제에 대한 자세한 정보는 백준 | 11650번 : 좌표 정렬하기에서 확인할 수 있다.
import java.io.*;
import java.util.*;
class Coordinate implements Comparable<Coordinate> {
int x;
int y;
public Coordinate(int x, int y) {
this.x = x;
this.y = y;
}
@Override
public int compareTo(Coordinate o) {
if (this.x == o.x) {
return this.y - o.y;
}
return this.x - o.x;
}
@Override
public String toString() {
return this.x + " " + this.y + "\n";
}
}
public class Main {
public static void main(String[] args) throws Exception {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));
ArrayList<Coordinate> list = new ArrayList<>();
int n = Integer.parseInt(br.readLine());
for (int i = 0; i < n; i++) {
StringTokenizer temp = new StringTokenizer(br.readLine());
int x = Integer.parseInt(temp.nextToken());
int y = Integer.parseInt(temp.nextToken());
list.add(new Coordinate(x, y));
}
Collections.sort(list);
for (int i = 0; i < n; i++) {
bw.write(list.get(i).toString());
}
br.close();
bw.close();
}
}
메모리 : 53532KB
시간 : 808ms
문제를 보자마자 당연하게 class를 구현할 생각부터 했다. 풀고 나서 다른 풀이들을 찾아봤는데 2차원 배열에 저장 후
Arrays.sort(arr, new Comparator<int[]>() {});를 사용할 수 있다는 걸 깨달았다. 왜 자꾸 복잡한 쪽으로 생각이 가는지 모르겠다...