PS/BOJ
11650
easy16
2022. 5. 6. 20:59
좌표 정렬하기 : https://www.acmicpc.net/problem/11650
숏코드 : https://www.acmicpc.net/source/18085875
//Class Point 구현을 통한 풀이
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.*;
public class Main {
static int N;
static boolean DBG = false;
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
N = Integer.parseInt(br.readLine());
StringTokenizer st;
Point[] arr = new Point[N];
for (int i = 0; i < N; i++) {
st = new StringTokenizer(br.readLine());
arr[i] = new Point(Integer.parseInt(st.nextToken()), Integer.parseInt(st.nextToken()));
}
Arrays.sort(arr);
StringBuilder sb = new StringBuilder();
for (Point p : arr) {
sb.append(String.format("%d %d\n", p.x, p.y));
}
System.out.println(sb);
}
}
class Point implements Comparable<Point> {
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;
return this.x - o.x;
}
}
int[] 을 정렬하는 방법, Comparator를 Arrays.sort의 인자로 넘겨준다.
그러면 arr의 요소인 int[2] 크기 배열을 Comparator의 인자로 넘겨 정렬해준다.
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.*;
public class Main {
static int N;
static boolean DBG = false;
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
N = Integer.parseInt(br.readLine());
StringTokenizer st;
int[][] arr = new int[N][2];
for (int i = 0; i < N; i++) {
st = new StringTokenizer(br.readLine());
for (int j = 0; j < 2; j++)
arr[i][j] = Integer.parseInt(st.nextToken());
}
Arrays.sort(arr, (p1, p2) -> {
if (p1[0] == p2[0])
return p1[1] - p2[1];
else
return p1[0] - p2[0];
});
Arrays.sort(arr, new Comparator<int[]>() {
@Override
public int compare(int[] a, int[] b) {
if (a[0] == b[0])
return Integer.compare(a[1], b[1]);
else
return Integer.compare(a[0], b[0]);
}
});
StringBuilder sb = new StringBuilder();
for ( int [] ar : arr)
sb.append(String.format("%d %d\n",ar[0], ar[1]));
System.out.println(sb);
}
}