[leetcode]My Calendar II
链接:https://leetcode.com/problems/my-calendar-ii/
Question
Implement a MyCalendarTwo
class to store your events. A new event can be added if adding the event will not cause a triple booking.
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 numbers x
such that start <= x < end
.
A triple booking happens when three events have some non-empty intersection (ie., there is some time that is common to all 3 events.)
For each call to the method MyCalendar.book
, return true
if the event can be added to the calendar successfully without causing a triple 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
MyCalendar();
MyCalendar.book(10, 20); // returns true
MyCalendar.book(50, 60); // returns true
MyCalendar.book(10, 40); // returns true
MyCalendar.book(5, 15); // returns false
MyCalendar.book(5, 10); // returns true
MyCalendar.book(25, 55); // returns true
Explanation:
The first two events can be booked. The third event can be double booked.
The fourth event (5, 15) can't be booked, because it would result in a triple booking.
The fifth event (5, 10) can be booked, as it does not use time 10 which is already double booked.
The sixth event (25, 55) 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.
Note:
The number of calls to MyCalendar.book per test case will be at most 1000.
In calls to MyCalendar.book(start, end), start and end are integers in the range [0, 10^9].
Solution
// 这道题完全就不是用BST的解法。。
// 关键在于需要维护两个数组,一个是目前有的可以存在的区间,另一个是overlap的区间(double booking)
// 每次先比较overlapping的区间,看看是否有triple booking的区间;再比较intervals的区间,找出overlapping的部分加入到overlapping数组中
class MyCalendarTwo {
public:
typedef pair<int, int> Pair;
vector<Pair> intervals;
vector<Pair> overlapping;
MyCalendarTwo() {
this->intervals.clear();
this->overlapping.clear();
}
bool book(int start, int end) {
// 先看是否会出现triple booking
for (int i = 0; i < overlapping.size(); i++) {
// triple booking
if (!(start >= overlapping[i].second) && !(end <= overlapping[i].first)) {
return false;
}
}
// 找到新的overlapping的部分
for (int i = 0; i < intervals.size(); i++) {
int s = -1;
int f = -1;
if (!(start >= intervals[i].second) && !(end <= intervals[i].first)) {
s = max(intervals[i].first, start);
f = min(intervals[i].second, end);
}
if (s != -1) {
overlapping.push_back(Pair(s, f));
}
}
intervals.push_back(Pair(start, end));
return true;
}
};
思路:关键在于需要维护两个数组,一个是目前有的可以存在的区间,另一个是overlap的区间(double booking)。每次先比较overlapping的区间,看看是否有triple booking的区间;再比较intervals的区间,找出overlapping的部分加入到overlapping数组中