|
| 1 | +# Time: O(n^2) |
| 2 | +# Space: O(n) |
| 3 | + |
| 4 | +# Implement a MyCalendarTwo class to store your events. |
| 5 | +# A new event can be added if adding the event will not cause a triple booking. |
| 6 | +# |
| 7 | +# Your class will have one method, book(int start, int end). |
| 8 | +# Formally, this represents a booking on the half open interval [start, end), |
| 9 | +# the range of real numbers x such that start <= x < end. |
| 10 | +# |
| 11 | +# A triple booking happens when three events have some non-empty intersection |
| 12 | +# (ie., there is some time that is common to all 3 events.) |
| 13 | +# |
| 14 | +# For each call to the method MyCalendar.book, |
| 15 | +# return true if the event can be added to the calendar successfully without causing a triple booking. |
| 16 | +# Otherwise, return false and do not add the event to the calendar. |
| 17 | +# |
| 18 | +# Your class will be called like this: MyCalendar cal = new MyCalendar(); MyCalendar.book(start, end) |
| 19 | +# Example 1: |
| 20 | +# MyCalendar(); |
| 21 | +# MyCalendar.book(10, 20); // returns true |
| 22 | +# MyCalendar.book(50, 60); // returns true |
| 23 | +# MyCalendar.book(10, 40); // returns true |
| 24 | +# MyCalendar.book(5, 15); // returns false |
| 25 | +# MyCalendar.book(5, 10); // returns true |
| 26 | +# MyCalendar.book(25, 55); // returns true |
| 27 | +# |
| 28 | +# Explanation: |
| 29 | +# The first two events can be booked. The third event can be double booked. |
| 30 | +# The fourth event (5, 15) can't be booked, because it would result in a triple booking. |
| 31 | +# The fifth event (5, 10) can be booked, as it does not use time 10 which is already double booked. |
| 32 | +# The sixth event (25, 55) can be booked, as the time in [25, 40) will be double booked with the third event; |
| 33 | +# the time [40, 50) will be single booked, and the time [50, 55) will be double booked with the second event. |
| 34 | +# |
| 35 | +# Note: |
| 36 | +# - The number of calls to MyCalendar.book per test case will be at most 1000. |
| 37 | +# - In calls to MyCalendar.book(start, end), start and end are integers in the range [0, 10^9]. |
| 38 | + |
| 39 | +class MyCalendarTwo(object): |
| 40 | + |
| 41 | + def __init__(self): |
| 42 | + self.__overlaps = [] |
| 43 | + self.__calendar = [] |
| 44 | + |
| 45 | + |
| 46 | + def book(self, start, end): |
| 47 | + """ |
| 48 | + :type start: int |
| 49 | + :type end: int |
| 50 | + :rtype: bool |
| 51 | + """ |
| 52 | + for i, j in self.__overlaps: |
| 53 | + if start < j and end > i: |
| 54 | + return False |
| 55 | + for i, j in self.__calendar: |
| 56 | + if start < j and end > i: |
| 57 | + self.__overlaps.append((max(start, i), min(end, j))) |
| 58 | + self.__calendar.append((start, end)) |
| 59 | + return True |
| 60 | + |
| 61 | + |
| 62 | +# Your MyCalendarTwo object will be instantiated and called as such: |
| 63 | +# obj = MyCalendarTwo() |
| 64 | +# param_1 = obj.book(start,end) |
0 commit comments