코딩 테스트/6. Sorting and Searching
Q6 - 7 좌표 정렬
길동이이이잉
2021. 10. 25. 21:47
728x90
반응형
7. 좌표 정렬
* 설명
N개의 평면상의 좌표(x, y)가 주어지면 모든 좌표를 오름차순으로 정렬하는 프로그램을 작성하세요.
정렬기준은 먼저 x값의 의해서 정렬하고, x값이 같을 경우 y값에 의해 정렬합니다.
* 입력
첫째 줄에 좌표의 개수인 N(3<=N<=100,000)이 주어집니다.
두 번째 줄부터 N개의 좌표가 x, y 순으로 주어집니다. x, y값은 양수만 입력됩니다.
* 출력
N개의 좌표를 정렬하여 출력하세요.
* 예시 입력 1
5
2 7
1 3
1 2
2 5
3 6
* 예시 출력 1
1 2
1 3
2 5
2 7
3 6
import java.util.ArrayList;
import java.util.Collections;
import java.util.Scanner;
class Point implements Comparable<Point>{
public 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;
//오름차순이 되게 하려면 음수값이 리턴되어야함!!!
}else{
return this.x - o.x;
}
}
}
public class Main {
public static void main(String[] args){
Scanner in = new Scanner(System.in);
int in1 = in.nextInt();
ArrayList<Point> arr = new ArrayList<>();
for (int i = 0; i < in1; i++){
int x = in.nextInt();
int y = in.nextInt();
arr.add(new Point(x, y));
}
Collections.sort(arr);
for (Point o : arr){
System.out.println(o.x + " " + o.y);
}
}
}
import java.util.*;
class Point implements Comparable<Point>{
public 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;
else return this.x-o.x;
}
}
class Main {
public static void main(String[] args){
Scanner kb = new Scanner(System.in);
int n=kb.nextInt();
ArrayList<Point> arr=new ArrayList<>();
for(int i=0; i<n; i++){
int x=kb.nextInt();
int y=kb.nextInt();
arr.add(new Point(x, y));
}
Collections.sort(arr);
for(Point o : arr) System.out.println(o.x+" "+o.y);
}
}
728x90
반응형