[문제]
2차원 평면 위의 점 N개가 주어진다.
좌표를 y좌표가 증가하는 순으로, y좌표가 같으면 x좌표가 증가하는 순서로 정렬한 다음 출력하는 프로그램을 작성하시오.
11651번: 좌표 정렬하기 2
첫째 줄에 점의 개수 N (1 ≤ N ≤ 100,000)이 주어진다. 둘째 줄부터 N개의 줄에는 i번점의 위치 xi와 yi가 주어진다. (-100,000 ≤ xi, yi ≤ 100,000) 좌표는 항상 정수이고, 위치가 같은 두 점은 없다.
www.acmicpc.net
[풀이]
import java.io.*;
import java.util.*;
public class Main {
public static void main(String[] args) throws IOException {
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
int test=Integer.parseInt(br.readLine());
List<int[]> list=new ArrayList<>();
for(int i=0;i<test;i++) {
String input=br.readLine();
String[] tmp=input.split(" ");
int x=Integer.parseInt(tmp[0]);
int y=Integer.parseInt(tmp[1]);
list.add(new int[] {x, y});
}
list.sort(new Comparator<int[]>() {
@Override
public int compare(int[] i1, int[] i2) {
if(i1[1]==i2[1]) return i1[0] - i2[0];
return i1[1] - i2[1];
}
});
for(int[] arr:list) System.out.println(arr[0]+" "+arr[1]);
}
}
첫 번째 풀이이다. 맞았기는 하지만 시간이 오래 걸려서 list를 정렬하지 않고 배열을 정렬해야겠다는 생각이 들었다.

또한 시스템 아웃보다 빠른 BufferedWriter를 사용할건데,
BufferedWriter의 경우 정수형은 다 String.valueOf를 통해 바꾸어주어야 한다.
그래서 StringBuilder를 사용해보기로 했다.
최종 코드는 아래와 같다.
import java.io.*;
import java.util.Arrays;
import java.util.Comparator;
public class Main {
public static void main(String[] args) throws IOException {
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
BufferedWriter bw=new BufferedWriter(new OutputStreamWriter(System.out));
int n=Integer.parseInt(br.readLine());
int[][] coor=new int[n][2];
for(int i=0;i<n;i++) {
String input=br.readLine();
String[] tmp=input.split(" ");
coor[i][0]=Integer.parseInt(tmp[0]);
coor[i][1]=Integer.parseInt(tmp[1]);
}
br.close();
Arrays.sort(coor, new Comparator<int[]>() {
@Override
public int compare(int[] arr1, int[] arr2) {
if(arr1[1]==arr2[1]) return arr1[0] - arr2[0];
return arr1[1] - arr2[1];
}
});
StringBuilder sb=new StringBuilder();
for(int[] arr:coor) sb.append(arr[0]+" "+arr[1]+"\n");
bw.write(sb.toString());
bw.close();
}
}
결과는 이렇다.

이전 코드보다 2배는 빠르다. 역시 list 정렬보다는 배열 정렬이 빠른건가..
사이즈만 확실하게 안다면 list보다 배열이 더 효율이 좋은 것 같다.
어쨌든 오늘의 코테 완료~
'👩🏻💻 코테' 카테고리의 다른 글
| 백준 S4 10816 : 숫자 카드 2 🅾️ (0) | 2024.04.07 |
|---|---|
| 백준 S4 4949 : 균형잡힌 세상 🅾️ (0) | 2024.04.06 |
| 백준 B1 1259 : 팰린드롬수 🅾️ (0) | 2024.04.04 |
| 백준 S4 1920 : 수 찾기 🅾️ (0) | 2024.04.03 |
| 백준 S5 1676 : 팩토리얼 0의 개수 🅾️ (0) | 2024.04.02 |