729. My Calendar I
Question
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
andend
that represents a booking on the half-open interval[start, end)
, the range of real numbersx
such thatstart <= x < end
.Implement the
MyCalendar
class:
MyCalendar()
Initializes the calendar object.boolean book(int start, int end)
Returnstrue
if the event can be added to the calendar successfully without causing a double booking. Otherwise, returnfalse
and do not add the event to the calendar.
Solution
有更快速的解法,需要用到TreeMap,有时间再研究。
使用一个队列记录已经预定的范围。
添加无穷大到队列中,方便后期计算。
当预定新的时间段时,遍历队列,如果上一个数组的最大值小于start和end且当前遍历数组大于start和end,则可以预定,将当前的数组插入当前位置,并返回true。
如果没有满足条件的,则返回false。
Code
1 | class MyCalendar { |
729. My Calendar I