[알고리즘] Sorting and Searching(정렬, 이분검색과 결정알고리즘) - 좌표정렬(compare To)(7) : (JAVA)

ho's·2022년 6월 15일
0

🍺 좌표정렬

🥗 문제

🥗 풀이

🌍 내 풀이

  • 입력 갯수를 입력받는다.
  • 2중 배열을 이용해 값을 입력받는다.
  • 1차원 배열은 Arrays.sort()를 이용해 간단하게 정렬이 된다.
  • 2차원 배열이기 때문에 Arrays.sort() Comparator를 이용해 정렬하도록 하자.

🥗 소스코드

🌍 내 풀이

package algolecture;

import java.util.Arrays;
import java.util.Comparator;
import java.util.Scanner;

public class Main49 {
    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);
        int cnt = scan.nextInt();
        int[][] arr = new int[cnt][2];
        for(int i=0;i<cnt;i++){
            for(int j=0;j<2;j++){
                arr[i][j] = scan.nextInt();
            }
        }

        Arrays.sort(arr, new Comparator<int[]>() {
            @Override
            public int compare(int[] o1, int[] o2) {
                if(o1[0] == o2[0]){
                    return o1[1] - o2[1];
                }else {
                    return o1[0] -o2[0];
                }
            }
        });

        for(int i=0;i<cnt;i++){
            for(int j=0;j<2;j++){
                System.out.print(arr[i][j]+" ");
            }
            System.out.println();
        }
    }
}

위의 코드를 보고 실행을 시키면 아래와 같은 결과가 나온다.

결과는...

뭐가 틀린지 잘 모르겠다.

🌍 강의 풀이

package algolecture;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Scanner;

// 제네릭 타입 Point클래스의 객체를 정렬한다.!
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 Main49lec {
    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);
    }
}
profile
그래야만 한다

0개의 댓글