티스토리 뷰

algorithm

11650 - 좌표 정렬하기

tonirr 2020. 5. 11. 08:03

 

  • Comparator인터페이스를 이용해서 compare 메소드를 오버라이딩하여 정렬했다.
  • sort함수에 arr을 받고 Comparator를 생성해주면서 compare 메소드를 오버라이딩한다.
public class Main {
	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		int n = sc.nextInt();
		int arr[][] = new int[n][2];
		
		for(int i = 0; i < n; i++) {
			for(int j = 0; j < arr[i].length; j++) {
				arr[i][j] = sc.nextInt();
			}
		}
		
		Arrays.sort(arr, new Comparator<int[]>() {

			@Override
			public int compare(int[] o1, int[] o2) {
				if(o1[0] == o2[0])
					return Integer.compare(o1[1], o2[1]);
					
				return Integer.compare(o1[0], o2[0]);
			}
			
		});
		
		for(int i = 0; i < arr.length; i++) {
			System.out.println(arr[i][0]+" "+arr[i][1]);
		}
	}
}

'algorithm' 카테고리의 다른 글

[Algorithm] LeetCode 202.happy number using HashSet  (0) 2020.05.18
10989 수 정렬하기 3  (0) 2020.05.16
2751 - 수 정렬하기 2  (0) 2020.05.11
[DP] 11052 카드 구매하기  (0) 2020.05.05
다이나믹 프로그래밍 문제 정리  (0) 2020.05.05
댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2025/08   »
1 2
3 4 5 6 7 8 9
10 11 12 13 14 15 16
17 18 19 20 21 22 23
24 25 26 27 28 29 30
31
글 보관함