작심삼일

[LeetCode] 729 | My Calendar I | Python 본문

스터디/코테

[LeetCode] 729 | My Calendar I | Python

yun_s 2022. 8. 3. 09:36
728x90
반응형

문제 링크: https://leetcode.com/problems/my-calendar-i/


문제

You are implementing a program to use as your calendar. We can add a new event if adding the event will not cause a double booking.

A double booking happens when two events have some non-empty intersection (i.e., some moment is common to both events.).

The event can be represented as a pair of integers start and end that represents a booking on the half-open interval [start, end), the range of real numbers x such that start <= x < end.

Implement the MyCalendar class:

  • MyCalendar() Initializes the calendar object.
  • boolean book(int start, int end) Returns true if the event can be added to the calendar successfully without causing a double booking. Otherwise, return false and do not add the event to the calendar.

조건

  • 0 <= start < end <= $10^9$
  • At most 1000 calls will be made to book.

내 풀이

기존까지 예약 내역을 self.booked에 저장해둔다.

만약 새로운 예약 내역([start, end])가 기존의 내역([s, e])와 겹치면 False를 리턴한다.

겹치는 경우는 다음과 같이 세가지가 있다.

첫째, start가 기존의 내역 사이에 있는 경우

둘째, end가 기존의 내역 사이에 있는 경우

셋째, 새로운 예약 내역 사이에 기존의 내역이 있는 경우

 

위 세가지 경우에 해당하지 않으면 self.booked에 추가하고 True를 리턴한다.


코드

class MyCalendar:

    def __init__(self):
        self.booked = []

    def book(self, start: int, end: int) -> bool:
        for s, e in self.booked:
            if s <= start < e:
                return False
            elif s < end <= e:
                return False
            elif start <= s and e < end:
                return False
        
        self.booked.append([start, end])
        return True


# Your MyCalendar object will be instantiated and called as such:
# obj = MyCalendar()
# param_1 = obj.book(start,end)
728x90
반응형
Comments