티스토리 뷰

 

문제는 위와 같으며 좌표 데이터를 딕셔너리 형태로 리스트에 담아 기본으로 제공하는 sort 메소드를 통해 문제를 해결하였습니다.

 

파이썬 코드는 다음과 같습니다. 파이썬의 정렬 함수(sort, sorted) 는 기본적으로 앞 인덱스부터 순서대로 비교하면서 정렬하기 때문에 x 를 기준으로 정렬 후 같으면 y를 기준으로 정렬합니다. 따라서 따로 key 속성을 정의하지 않아도 됩니다.

from sys import stdin

n = int(stdin.readline())
position = list()
for _ in range(n):
    x, y = map(int, stdin.readline().split())
    position.append((x, y))

position.sort()  # x 키를 기준으로 정렬 후 같으면 y 키를 기준으로 정렬 
for pos in position:
    print(pos[0], pos[1])

 

자바 코드는 다음과 같습니다.

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.*;

public class Main {
    public static void main(String[] args) throws Exception {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

        int n = Integer.parseInt(br.readLine());
        List<HashMap<String, Object>> position = new ArrayList<>();
        for (int i = 0; i < n; i++) {
            int[] xy = Arrays.stream(br.readLine().split(" ")).mapToInt(Integer::parseInt).toArray();
            HashMap<String, Object> tmp = new HashMap<>();
            tmp.put("x", xy[0]);
            tmp.put("y", xy[1]);
            position.add(tmp);
        }

        Collections.sort(position, new Comparator<HashMap<String, Object>>() {
            @Override
            public int compare(HashMap<String, Object> o1, HashMap<String, Object> o2) {
                Integer x1 = (Integer) o1.get("x");
                Integer x2 = (Integer) o2.get("x");
                Integer y1 = (Integer) o1.get("y");
                Integer y2 = (Integer) o2.get("y");

                if (x1.compareTo(x2) == 0) {  // x 키 값을 비교한 결과가 같은 경우
                    return y1.compareTo(y2);  // y 키 값을 기준으로 비교
                } else {
                    return x1.compareTo(x2);  // x 키 값이 다른 경우 x 키 값을 기준으로 비교
                }
            }
        });

        for (int i = 0; i < position.size(); i++) {
            System.out.println(position.get(i).get("x") + " " + position.get(i).get("y"));
        }
    }
}
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2025/03   »
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
글 보관함