#731
My Calendar II
specialist · 670 · lc medium +30 · 62.9% accepted · 2,270 likes · top 65%
Description
Build a calendar that allows double-bookings but rejects any event that would cause a triple-booking — a moment shared by three or more events. Events are represented as half-open intervals [startTime, endTime).
Implement the MyCalendarTwo class:
- MyCalendarTwo() Creates an empty calendar.
- boolean book(int startTime, int endTime) Adds the event and returns true if it does not create a triple-booking; otherwise returns false and discards the event.
Example 1:
Input
["MyCalendarTwo", "book", "book", "book", "book", "book", "book"]
[[], [10, 20], [50, 60], [10, 40], [5, 15], [5, 10], [25, 55]]
Output
[null, true, true, true, false, true, true]
Example 2:
Explanation
MyCalendarTwo myCalendarTwo = new MyCalendarTwo();
myCalendarTwo.book(10, 20); // return True, The event can be booked.
myCalendarTwo.book(50, 60); // return True, The event can be booked.
myCalendarTwo.book(10, 40); // return True, The event can be double booked.
myCalendarTwo.book(5, 15); // return False, The event cannot be booked, because it would result in a triple booking.
myCalendarTwo.book(5, 10); // return True, The event can be booked, as it does not use time 10 which is already double booked.
myCalendarTwo.book(25, 55); // return True, The event can be booked, as the time in [25, 40) will be double booked with the third event, the time [40, 50) will be single booked, and the time [50, 55) will be double booked with the second event.
Code
1
2
3
4
5
6
7
8
9
10
11
12