[JAVA 문제 풀이] 368. 호텔 대실

프로그래머스 (155651)
Stupefyee's avatar
Jul 08, 2025
[JAVA 문제 풀이] 368. 호텔 대실
notion image
 

내가 작성한 코드

import java.util.*; class Solution { public int solution(String[][] book_time) { // 시작 시간 기준으로 정렬 Arrays.sort(book_time, (a, b) -> a[0].compareTo(b[0])); // 현재 방들 체크아웃 시간(청소시간 포함)을 저장할 우선순위 큐 (오름차순 정렬) PriorityQueue<Integer> checkOutQ = new PriorityQueue<>(); for (String[] time : book_time) { int checkIn = toMinutes(time[0]); int checkOut = toMinutes(time[1]) + 10; // 청소시간 10분 포함 // 현재 방의 checkIn이 가장 빨리 체크아웃하는 방의 checkOut보다 크거나 같으면 → 방 재사용 if (!checkOutQ.isEmpty() && checkOutQ.peek() <= checkIn) { checkOutQ.poll(); // 가장 빨리 끝나는 방 제거하고 재사용 } // 새 방 or 재사용한 방의 종료 시간 추가 checkOutQ.offer(checkOut); } // 큐에 남아있는 방 수 == 필요한 최소 방 수 return checkOutQ.size(); } // 시간 문자열을 분으로 변환하는 메소드 public int toMinutes(String time) { String[] parts = time.split(":"); int hour = Integer.parseInt(parts[0]); int minute = Integer.parseInt(parts[1]); return hour * 60 + minute; } }
 

다른 사람의 코드

class Solution { public int solution(String[][] book_time) { int answer = 0; int[] howManyBooksInTime = new int[1440]; // 1440 = 24시간 * 60분 for (String[] book : book_time) { int start = toInt(book[0]); // 퇴실 + 청소 시간, 1439분(23:59) 중 최소값 // 문제 조건으로 자정을 넘기지 않는다는 항목 존재 >> min 필요 없음 int end = Math.min(1439, toInt(book[1]) + 10); // 해당 시간대에 카운트 증가 for (int i = start; i < end; i++) { howManyBooksInTime[i]++; } } // 시간대별로 가장 많은 방의 수를 찾음 for (int i = 0; i < 1440; i++) { answer = Math.max(answer, howManyBooksInTime[i]); } return answer; } // 시간 문자열을 분으로 변환하는 메소드 public int toInt(String s) { String[] ss = s.split(":"); return Integer.parseInt(ss[0]) * 60 + Integer.parseInt(ss[1]); } }
 
Share article

stupefyee