[코테 매일 풀기 4일차] 1028

HAHAING·2025년 10월 28일

코딩 테스트

목록 보기
13/30
post-thumbnail

백준 11650 좌표정렬하기

아이디어

  • ArrayList로 x,y 좌표를 받고, Collections.sort 사용하기
package boj_silver.p11650_좌표정렬;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.StringTokenizer;

public class Review1 {
    public static void main(String[] args) throws IOException {
        BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));
        StringTokenizer st;
        int N = Integer.parseInt(bf.readLine());

        ArrayList<int[]> list = new ArrayList<>(); //arrayList

        for (int i =0 ;i<N; i++){
            st = new StringTokenizer(bf.readLine());
            int x = Integer.parseInt(st.nextToken());
            int y = Integer.parseInt(st.nextToken());
            //방법1
            list.add(new int []{x,y});
        }//
        Collections.sort(list , (a,b) -> {
            if(a[0] ==b[0]){
                return a[1] - b[1];
            }
            return a[0] - b[0];
        });
        //출력
        for (int[] point: list){
            System.out.println(point[0] + " " + point[1]);
        }
    }
}

정렬하는 방법 1. Comparator 익명 클래스

Collections.sort(list, new Comparator<int[]> {
	@Override
    public int compare(int[] a, int[] b) {
    	//x좌표 오름차순, 같으면 y 오름차순 
        if (a[0] ==b[0]){
        	return a[1] - b[1]; 
        }
        return a[0] - b[0];// x비교 
        }
}

정렬하는 방법 2. 람다식

Collections.sort(list, (a,b) -> {
	if(a[0] == b[0])  return a[1] - b[1]; //overflow 방지를 위해 Integer.compare(a[1], b[1]) ; 
    return a[0]-b[0] 
}); 
Collections.sort(list, (a,b)-> 
	a[0] !=b[0] ? a[0]-b[0] : a[1]-b[1]
); 

정렬하는 방법 3. Comparator.comparing

Collections.sort(list, 
                Comparator.comparingInt((int[] a) -> a[0]) //x 기준
                          .thenComparingInt(a-> a[1]) //y 기준
); 
profile
따뜻한 시선으로 세상을 변화시키는 데이터사이언티스트

0개의 댓글