프로그래머스 - 내 풀이/프로그래머스 Lv2

[C#]프로그래머스/호텔 대실

ENUM01 2023. 4. 20. 00:13

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
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
using System;
using System.Collections.Generic;
using System.Globalization;
 
public class Solution
{
    public struct Booking
    {
        public TimeSpan startTime;
        public TimeSpan endTime;
 
        public Booking(TimeSpan startTime, TimeSpan endTime)
        {
            this.startTime = startTime;
            this.endTime = endTime;
        }
    }
 
    public int solution(string[,] book_time)
    {
        List<Booking> bookings = new List<Booking>();
 
        for (int i = 0; i < book_time.GetLength(0); i++)
        {
            //그냥 TimeSpan을 parsing하면, 문자열에 따라 TimeSpan이 다르게 변환되어 일부 케이스에서 오답이 발생한다.
            //ParseExact는 TimeSpan이 지정된 형식으로 변환되도록 보장한다.
            TimeSpan startTime = TimeSpan.ParseExact(book_time[i, 0], "hh\\:mm", CultureInfo.InvariantCulture);
            TimeSpan endTime = TimeSpan.ParseExact(book_time[i, 1], "hh\\:mm", CultureInfo.InvariantCulture).Add(TimeSpan.FromMinutes(10));
            bookings.Add(new Booking(startTime, endTime));
        }
 
        //입실시간이 빠른 것부터 방을 잡기 위해 정렬한다.
        bookings.Sort((a, b) => a.startTime.CompareTo(b.startTime));
 
        List<TimeSpan> rooms = new List<TimeSpan>();
 
        foreach (Booking booking in bookings)
        {
            bool roomAssigned = false;
 
            //방들 중에 시간이 비는 곳이 있는지 찾는다.
            for (int i = 0; i < rooms.Count; i++)
            {
                if (rooms[i] <= booking.startTime)
                {
                    //빈 시간이 있다면 새로운 대실의 퇴실시간으로 갱신한다.
                    rooms[i] = booking.endTime;
                    roomAssigned = true;
                    break;
                }
            }
 
            //시간이 비는 곳이 없다는 것. 방을 새로 추가한다.
            if (!roomAssigned)
                rooms.Add(booking.endTime);
        }
 
        return rooms.Count;
    }
}
 
cs