코딩테스트

[백준] 5635번 : 생일 자바(JAVA) 풀이

hye-ne 2024. 9. 12. 17:39

문제


문제 탐색하기

  • N : 학생의 수
  • 입력 : 학생의 이름과 생년월일 정보 N개
  • 출력 
    1. 가장 나이가 적은 사람의 이름
    2. 가장 나이가 많은 사람의 이름

가능한 시간복잡도

입력 범위 (1 ≤ N 100)

1. 입력 받기 : 입력받은 정보를 배열에 저장할 때 O(N)의 시간 복잡도를 가짐

2. 정렬 : Arrays.sort() 를 사용하는 경우 O(NlogN)의 시간 복잡도를 가진다 

3. 최종적으로 최악의 경우 시간 복잡도는 O(NlogN) 


코드 설계하기

  • 학생 수 N를  입력받는다.
  • Student 클래스를 만들어서 배열로 정보를 저장한다. (입력받는 정보의 타입이 달라서 클래스를 생성한 후, 배열로 담아주었다.)
  • 년도 달 → 일자 순으로 정렬해준다.
  • 가장 나이가 적은 사람과 많은 사람의 이름을 출력한다.

풀이 코드

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

public class Main {
	public static void main(String[] args) throws IOException {
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		int num = Integer.parseInt(br.readLine()); // 학생 수
		Student[] student = new Student[num]; // 학생 담을 S tudent 배열
		
		// 1. 입력받은 학생 Student 배열에 저장
		for(int i=0;i<num;i++) {
			StringTokenizer st = new StringTokenizer(br.readLine()); // 공백을 기준으로 자르기
			student[i] = new Student(st.nextToken(), Integer.parseInt(st.nextToken())
					, Integer.parseInt(st.nextToken()), Integer.parseInt(st.nextToken()));
		}
		
		// 2. 나이 오름차순으로 정렬
		Arrays.sort(student, new Comparator<Student>() {
			@Override
			public int compare(Student s1, Student s2) {
				if(s1.year != s2.year) { // 년도가 다르면 
					return s1.year - s2.year; // 년도 오름차순으로 정렬
				}else { // 년도가 같으면
					if(s1.month != s2.month) { // 달이 다르면
						return s1.month - s2.month; // 달로 오름차순 정렬
					}else {
						return s1.date - s2.date; // 일자로 오름차순 정렬
					}
				}
			}	
		});
		System.out.println(student[num-1].name); // 가장 나이가 적은 사람
		System.out.println(student[0].name); // 가장 나이가 많은 사람
	}
	
	// Student 클래스 생성
	public static class Student{
		String name;
		int date;
		int month;
		int year;
		
		public Student(String name, int date, int month, int year) {
			this.name = name;
			this.date = date;
			this.month = month;
			this.year = year;
		}
	}
}