본문 바로가기

백준 11650 - 좌표정렬하기

@sonic052025. 6. 17. 15:41

난이도

  실버V

 

 

문제

 

 

 

1.Point클래스

 

x,y를 저장하는 생성자와 x,y를 출력하는 printPoint함수를 가진 Point클래스를 만든다

 

class Point{
    int x,y;
    Point(int x,int y){
        this.x = x;
        this.y = y;
    }
    public void printPoint(){
        System.out.println(x+" "+y);
    }
}

 

 

 

2.인자가 2개인 Collections.sort()

3에서 서술할 Comparator가 들어가는 오름차순 정렬 메서드를 사용한다.

 

Collections.sort(arrl,new Comparator<Point>(){});

 

 

 

 

3.Comparator 생성 및 compare 메서드 구현

 

Comparaor는 인터페이스로, compare메서드를 구현해주어야한다. compare메서드를 원하는 대로 구현하면, 2의 Collections.sort에서 이를 반영하여 정렬하는 방식이다.

 

Collections.sort(arrl,new Comparator<Point>() {
    public int compare(Point a,Point b){
        if(a.x == b.x){
            return Integer.compare(a.y,b.y);
        }
        else{
            return Integer.compare(a.x,b.x);
        }
    }
});

 

 

 

최종

 

 

import java.util.*; 


class Point{
    int x,y;
    Point(int x,int y){
        this.x = x;
        this.y = y;
    }
    public void printPoint(){
        System.out.println(x+" "+y);
    }
}


public class Main {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        ArrayList<Point> arrl = new ArrayList<>();
        int N = scanner.nextInt();
        for(int i = 0;i < N;i++){
            Point p = new Point(scanner.nextInt(),scanner.nextInt());
            arrl.add(p);
        }
        Collections.sort(arrl,new Comparator<Point>() {
            public int compare(Point a,Point b){
                if(a.x == b.x){
                    return Integer.compare(a.y,b.y);
                }
                else{
                    return Integer.compare(a.x,b.x);
                }
            }
        });
        for(Point p : arrl){
            p.printPoint();
        }
    }
}

 

 

 

'개발' 카테고리의 다른 글

Node.js(with codecademy) - 5  (0) 2025.06.20
Node.js(with codecademy) - 4  (0) 2025.06.19
Node.js(with codecademy) - 3  (2) 2025.06.18
Node.js(with codecademy) - 2  (1) 2025.06.17
sonic05
@sonic05 :: sonic05 님의 블로그

sonic05 님의 블로그 입니다.

공감하셨다면 ❤️ 구독도 환영합니다! 🤗

목차