Algorithms/프로그래머스

[Lv2] 호텔 대실

hyunki.Dev 2023. 11. 8. 22:27

📌 문제

https://school.programmers.co.kr/learn/courses/30/lessons/155651

 

프로그래머스

코드 중심의 개발자 채용. 스택 기반의 포지션 매칭. 프로그래머스의 개발자 맞춤형 프로필을 등록하고, 나와 기술 궁합이 잘 맞는 기업들을 매칭 받으세요.

programmers.co.kr

 

 

📌 풀이

  • 주어진 문제의 배열을 오름차순으로 정렬한다.
  • 시간의 비교를 숫자로 바꿔서 숫자 비교로 바꾸거나 아니면 LocalTime을 사용해서 Time의 비교를 진행해도 된다.
  • 방의 할당은 PriorityQueue를 사용해서 할당한다.
    • PriorityQueue는 기본형을 사용시 우선순위가 항상 낮은 숫자가 먼저 나오게 된다.

 

📌 코드

import java.util.*;

class Solution {
    public int solution(String[][] book_time) {
        int answer = 0;
        
        // 배열 오름차순 정렬
        Arrays.sort(book_time, new Comparator<String[]>(){
           @Override
            public int compare(String[] o1, String[] o2){
                if(o1[0].equals(o2[0])){
                    return o1[1].compareTo(o2[1]);
                } else {
                    return o1[0].compareTo(o2[0]);
                }
            }
        });
        
        //예약 시간 정수로 변경
        int[][] time = new int[book_time.length][2];
        for(int i = 0; i < book_time.length; i++){

            int start_time = Integer.parseInt(book_time[i][0].replace(":",""));
            int end_time = Integer.parseInt(book_time[i][1].replace(":",""));
        
            end_time += 10;
            
            if(end_time % 100 >= 60){
                end_time += 40;
            }
            
            time[i][0] = start_time;
            time[i][1] = end_time;
        }
        
        // 예약 시간 별 객실 할당
        PriorityQueue<Integer> rooms = new PriorityQueue<>();
            
        for(int[] timeInt : time){
            if(rooms.size() == 0){
                //첫 예약일 경우 종료 시간 저장
                rooms.add(timeInt[1]);
                continue;
            }
            
            int earlisetEmptyRoom = rooms.peek();
            if(timeInt[0] >= earlisetEmptyRoom){
                rooms.poll();
                rooms.add(timeInt[1]);
            } else {
                rooms.add(timeInt[1]);
            }
        }
        return rooms.size();
    }
}