[JAVA] 백준 1931번 : 회의실 배정

조예빈·2024년 6월 29일
0

Coding Test

목록 보기
20/138

처음 코드

package silver1;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class num1931 {
    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        int N = Integer.parseInt(br.readLine());
        int cnt = 1;

        Integer[][] times = new Integer[N][2];
        for (int i = 0; i < N; i++) {
            String[] input = br.readLine().split(" ");
            times[i][0] = Integer.parseInt(input[0]); // 시작 시간
            times[i][1] = Integer.parseInt(input[1]); // 종료 시간
        }

        for (int i = 0; i < N - 1; i++) { //종료 시간을 기준으로 오름차순 정렬
            for (int j = i + 1; j < N; j++) {
                if (times[i][1] > times[j][1] || (times[i][1].equals(times[j][1]) && times[i][0] > times[j][0])) {
                    Integer[] temp = times[i];
                    times[i] = times[j];
                    times[j] = temp;
                }
            }
        }

        int endtime = times[0][1]; // 첫 번째 회의의 종료 시간
        for (int i = 1; i < N; i++) {
            if (times[i][0] >= endtime) {
                cnt++;
                endtime = times[i][1];
            }
        }

        System.out.println(cnt);
        br.close();
    }
}

시간 초과가 발생하였다 ㅠㅠ 그래서 찾아보니, Comparator라는 것을 사용해 주어야 한다고 한다... 새로운 인터페이스는 어려워서 기존 로직을 직접 구현하려고 했지만, 결국에는 사용해 주어야 하나 보다 ㅠㅠ

Comparator

  • 자바에서 객체의 비교를 지원하는 인터페이스
  • 주로 정렬이나 자료구조에서 객체들을 비교하고 정렬할 때 사용됨

정의

public interface Comparator<T> {
    int compare(T o1, T o2);
    boolean equals(Object obj);
}
  • 두 객체 o1과 o2를 비교하여 정수 값을 반환함
  • 반환 값이 0이면 o1과 o2가 같음
  • 반환 값이 음수이면 o1이 o2보다 작음
  • 반환 값이 양수이면 o1이 o2보다 큼
  • 즉, 반환값만 넘겨주면 그 반환값에 따라서 Arrays.sort가 알아서 정렬을 해 주는 것 -> 우리는 어떤 값을 '기준'으로 정렬할 것인지만 생각하면 됨

정답 코드

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.Comparator;

public class Main {
    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        int N = Integer.parseInt(br.readLine());
        int cnt = 1;

        Integer[][] times = new Integer[N][2];
        for (int i = 0; i < N; i++) {
            String[] input = br.readLine().split(" ");
            times[i][0] = Integer.parseInt(input[0]); // 시작 시간
            times[i][1] = Integer.parseInt(input[1]); // 종료 시간
        }

        Arrays.sort(times, new Comparator<Integer[]>() { //2차원 배열 times의 각 요소인 Integer[] 비교
            @Override
            public int compare(Integer[] o1, Integer[] o2) { //두 개의 객체를 받아 비교하고 정수 값 반환
                if (o1[1] == o2[1]) { //종료시간이 같으면
                    return Integer.compare(o1[0], o2[0]); //o1과 o2를 비교해서 반환하는 값에 따라 Arrays.sort가 알아서 정렬해줌 -> 어떤 값을 기준으로 정렬할지만 정하면 되는 것
                }
                return o1[1] - o2[1];
            }
        });

        int endtime = times[0][1]; // 첫 번째 회의의 종료 시간
        for (int i = 1; i < N; i++) {
            if (times[i][0] >= endtime) {
                cnt++;
                endtime = times[i][1];
            }
        }

        System.out.println(cnt);
        br.close();
    }
}

profile
컴퓨터가 이해하는 코드는 바보도 작성할 수 있다. 사람이 이해하도록 작성하는 프로그래머가 진정한 실력자다. -마틴 파울러

0개의 댓글