My Calendar II
Implement aMyCalendarTwo
class to store your events. A new event can be added if adding the event will not cause atriplebooking.
Your class will have one method,book(int start, int end)
. Formally, this represents a booking on the half open interval[start, end)
, the range of real numbersx
such thatstart <= x < end
.
Atriple bookinghappens whenthreeevents have some non-empty intersection (ie., there is some time that is common to all 3 events.)
For each call to the methodMyCalendar.book
, returntrue
if the event can be added to the calendar successfully without causing atriplebooking. Otherwise, returnfalse
and do not add the event to the calendar.
Your class will be called like this:
MyCalendar cal = new MyCalendar();
MyCalendar.book(start, end)
Example 1:
Note:
The number of calls to
MyCalendar.book
per test case will be at most1000
.In calls to
MyCalendar.book(start, end)
,start
andend
are integers in the range[0, 10^9]
.
Solution & Analysis
Approach #1: Brute Force
Maintain a list of bookings and a list of double bookings. When booking a new event [start, end)
, if it conflicts with a double booking, it will have a triple booking and be invalid. Otherwise, parts that overlap the calendar will be a double booking.
Evidently, two events[s1, e1)
and[s2, e2)
do_not_conflict if and only if one of them starts after the other one ends: eithere1 <= s2
ORe2 <= s1
. By De Morgan's laws, this means the events conflict whens1 < e2
ANDs2 < e1
.
If our event conflicts with a double booking, it's invalid. Otherwise, we add conflicts with the calendar to our double bookings, and add the event to our calendar.
128 ms, faster than 79.28%
Time Complexity:O(N^2), whereNNis the number of events booked. For each new event, we process every previous event to decide whether the new event can be booked. This leads to ∑kN O(k) = O(N^2) complexity.
Space Complexity: O(N), the size of the
calendar
.
Approach #2: Boundary Count: Use TreeMap + Loop
TreeMap用来排序所有的起始、终止节点,方便扫描线。ongoing变量记录当前的重叠的次数。
TreeMap相比于单纯用List存节点再排序的方法,更方便每次的增量更新,而List则需要每次全部排列之后再扫描,book()的时间复杂度是O(nlogn + n), worst case O(nlogn + nlogn)。
用TreeMap则book()只需要O(logn + n)时间,worst case每次不能插入新booking,或者说每次都有ongoing >= 3的情形要更新,则O(logn + n*logn)。
Time Complexity: 对于N次Booking来说,平均时间复杂度则为O(n(logn + n)) ~ O(n^2 + nlogn)
Space Complexity: O(N)
191 ms, faster than 57.15%
Reference
Last updated