题目描述
Implement a MyCalendar
class to store your events. A new event can be added if adding the event will not cause a double booking.
Your class will have the method, book(int start, int end)
. Formally, this represents a booking on the half open interval [start, end)
, the range of real numbers x
such that start <= x < end
.
A double booking happens when two events have some non-empty intersection (ie., there is some time that is common to both events.)
For each call to the method MyCalendar.book
, return 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.
Your class will be called like this: MyCalendar cal = new MyCalendar();``MyCalendar.book(start, end)
Example 1:
MyCalendar();
MyCalendar.book(10, 20); // returns true
MyCalendar.book(15, 25); // returns false
MyCalendar.book(20, 30); // returns true
Explanation:
The first event can be booked. The second can't because time 15 is already booked by another event.
The third event can be booked, as the first event takes every time less than 20, but not including 20.
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]
.
题意:实现一个 MyCalendar
类来存放你的日程安排。如果要添加的时间内没有其他安排,则可以存储这个新的日程安排。
MyCalendar
有一个 book(int start, int end)
方法。它意味着在 start
到 end
时间内增加一个日程安排,注意,这里的时间是半开区间,即 [start, end)
, 实数 x
的范围为, start <= x < end
。
当两个日程安排有一些时间上的交叉时(例如两个日程安排都在同一时间内),就会产生重复预订。
每次调用 MyCalendar.book
方法时,如果可以将日程安排成功添加到日历中而不会导致重复预订,返回 true。否则,返回 false 并且不要将该日程安排添加到日历中。
请按照以下步骤调用 MyCalendar
类: MyCalendar cal = new MyCalendar(); MyCalendar.book(start, end)
算法1
(map) $O(n^logn)$
题解:我们需要使用一个数据结构来维护若干个不相交的区间,该数据结构能够支持高效的插入和查询,我们选择map<int,int>
来维护左右端点。每当来了一个订单的时候,我们需要查询是否冲突,那么我们使用lower_bound()
函数查找到待插入位置的下一个区间。这样我们只需要分别判断左端点和上一个区间的右端点是否冲突和右端点和下一个区间的左端点是否冲突即可。
class MyCalendar {
public:
map<int,int> hash;
MyCalendar() {
}
bool book(int start, int end) {
if(hash.size() == 0)
{
hash[start] = end;
return true;
}
auto it = hash.lower_bound(start);
bool flag = false;
if(it == hash.begin() && end <= it->first)
flag = true;
else if(it == hash.end() && (--it)->second <= start)
flag = true;
else
{
auto pre = it;
pre --;
if(pre->second <= start && end <= it->first)
flag = true;
}
if(flag)
{
hash[start] = end;
return true;
}
return false;
}
};