티스토리 뷰

import java.io.*;
import java.util.*;

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

class Main {
public static void main(String[] args) throws IOException {
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
int count = Integer.parseInt(in.readLine());
ArrayList<Point> arrayList = new ArrayList<>();
for(int i=0; i<count; ++i) {
String[] input = in.readLine().split(" ");
int x = Integer.parseInt(input[0]);
int y = Integer.parseInt(input[1]);
arrayList.add(new Point(x, y));
}
Collections.sort(arrayList, new Comparator<Point>() {
@Override
public int compare(Point o1, Point o2) {
if(o1.x == o2.x) {
if(o1.y < o2.y) {
return -1;
} else {
return 1;
}
} else if(o1.x < o2.x) {
return -1;
} else {
return 1;
}
}
});
for(int i=0; i<count; ++i) {
System.out.print(arrayList.get(i).x + " ");
System.out.print(arrayList.get(i).y);
System.out.println();
}
}
}



[정리]

Collections.sort()의 두 번째 인자로 정렬 방법을 구현한 객체?를 넣을 수 있다.


1, 0, -1을 반환하는 기준을 대충 이해한 것을 적어보면...

if문의 조건에 들어가는 식의 부등호가 왼쪽일 때 true일 때 1을 반환하면 왼쪽 값, -1을 반환하면 오른쪽 값이 나오는 것 같다..?

뭐 맞았으니까 맞겠지.

아무튼 Java에서도 인자에 Comparator 인스턴스를 넣어 정렬 기준을 커스터마이징 할 수 있다!


이 문제는 좌표를 정렬하는 문제이므로

아래 Swift에서는 튜플을 사용한 것처럼

Java에서는 클래스를 하나 만들어주어 해당 클래스 타입을 사용하는? Comparator 인스턴스를 만들어준다.




Swift로는 sort()로 간단하게 구현할 수 있다.


let count = Int(readLine()!)!

var array = [(Int, Int)]()

for _ in 0..<count {

    let input = readLine()!.split(separator: " ").map { Int($0)! }

    array.append((input.first!, input.last!))

}

array.sort { (first, second) -> Bool in

    if first.0 == second.0 {

        return first.1 < second.1

    }

    return first.0 < second.0

}

for i in array {

    print(i.0, i.1)

}


'Algorithm > Baekjoon Online Judge' 카테고리의 다른 글

10814번 '나이순 정렬'  (0) 2018.08.05
11651번 '좌표 정렬하기 2'  (0) 2018.08.05
2751번 '수 정렬하기 2'  (0) 2018.08.04
2004번 '조합 0의 개수'  (0) 2018.08.01
1676번 '팩토리얼 0의 개수'  (0) 2018.08.01
댓글
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
TAG
more
«   2025/03   »
1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31
글 보관함