https://www.acmicpc.net/problem/11651
11651번: 좌표 정렬하기 2
첫째 줄에 점의 개수 N (1 ≤ N ≤ 100,000)이 주어진다. 둘째 줄부터 N개의 줄에는 i번점의 위치 xi와 yi가 주어진다. (-100,000 ≤ xi, yi ≤ 100,000) 좌표는 항상 정수이고, 위치가 같은 두 점은 없다.
www.acmicpc.net
문제 풀이
다음은 간단하게 정렬을 하는 문제입니다. 사실 딱히 이해가 필요없이 y에 대해서 오름차순 정렬하는데 y가 같으면 x로 오름차순 정렬하는 비교적 쉬운 문제네요
여러가지 정렬이 있겠지만 최대한 객체지향적으로 클래스를 만들어서 comparable을 구현해보았습니다.
코드
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.StringTokenizer;
class Point implements Comparable<Point> {
int x;
int y;
public Point(int x, int y) {
this.x = x;
this.y = y;
}
@Override
public int compareTo(Point other) {
// y에 대한 오름차순 정렬
if (this.y != other.y) {
return this.y - other.y;
}
// y 값이 같은 경우 x에 대한 오름차순 정렬
return this.x-other.x;
}
}
public class Main {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringBuilder sb = new StringBuilder();
StringTokenizer st;
int n = Integer.parseInt(br.readLine());
Point[] points = new Point[n];
while (n-- > 0) {
st = new StringTokenizer(br.readLine());
points[n] = new Point(Integer.parseInt(st.nextToken()), Integer.parseInt(st.nextToken()));
}
Arrays.sort(points);
Arrays.stream(points).forEach(i -> sb.append(i.x + " " + i.y+"\n"));
System.out.println(sb);
}
}
쉬운 문제여서 그런지 1트 성공 기분 좋네요 ㅎㅎ
사실 객체로 만들 필요 없이 배열로 만들어 두고 Comparator로 익명함수 넣어서 구현하는 게 더 빠르긴 했겠네요
편하신 걸로 작성하시면 될 것 같아요
'Coding Test > 백준' 카테고리의 다른 글
[백준] 연구소 - 자바 (0) | 2023.07.11 |
---|---|
[백준] 1003 피보나치 함수 - 자바 (0) | 2023.07.11 |
[백준] 11000 강의실 배정 - 자바 (0) | 2023.07.11 |
[백준] 2217번 로프 - 자바 (0) | 2023.07.11 |
[백준] 2751 수 정렬하기 - 자바 (0) | 2023.07.11 |