731. My Calendar II
Implement a MyCalendarTwo class tostore your events. A new event can be added if adding the event will not causea triple booking.
Your class will have one method, book(intstart, int end). Formally,this represents a booking on the half open interval [start, end), the rangeof real numbers x such that start <= x< end.
A triple booking happens when three events havesome non-empty intersection (ie., there is some time that is common to all 3events.)
For each call to the method MyCalendar.book, return true if the eventcan be added to the calendar successfully without causing atriple booking.Otherwise, return false and do notadd the event to the calendar.
Your class will be called like this: MyCalendarcal = new MyCalendar(); MyCalendar.book(start,end)
Example 1:
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 wouldresult in a triple booking.
The fifth event (5, 10) can be booked, as it does not usetime 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 pertest case will be at most 1000.
· In calls to MyCalendar.book(start, end), start and end areintegers in the range [0, 10^9].
不断向数组中插入一个范围,假如它和其他两个范围重叠了,那么返回false,假如没有,那么将这个范围插入,这题我使用了一个数组,将数组中的范围按照start从小到大排序,如果给的book合法,就按照排序的顺序将它插入,如果不合法,就返回false,这题难都不难,就是逻辑很复杂,很容易把人绕晕,以后在解这样的题目的时候要记得 if条件语句里面的等于号要双写,感叹号要注意,大于小于也要注意
MyCalendarTwo() {
}
vector <pair<int, int>> theBooks;
bool book(int start, int end) {
int mark = -1;
int stage = 0; int theC = 0,theD=0;
for (int i = 0; i <theBooks.size(); i++)
{
if (theBooks[i].first < start)
{
if (theBooks[i].second > start)
{
if (stage == 0)
{
stage= 1; theC = theBooks[i].second;
}
else
if (stage == 1)
{
return false;
}
}
}
else
{
if(mark==-1) mark =i;
if (theBooks[i].first < end)
{
if (stage == 0)
{
stage= 2; theC = theBooks[i].first; theD= theBooks[i].second;
}
else
{
if (stage == 2)
{
if (theBooks[i].first >= theD)
{
stage= 2;
theC= theBooks[i].first; theD = theBooks[i].second;
}
else
{
return false;
}
}
if (stage == 1)
{
if (theBooks[i].first < theC)
{
return false;
}
else
{
stage= 2;
theC= theBooks[i].first; theD = theBooks[i].second;
}
}
}
}
else
{
theBooks.insert(theBooks.begin()+ mark, pair<int, int>(start, end));
return true;
}
}
}
if (mark == -1)
{
theBooks.push_back(pair<int, int>(start, end));
return true;
}
else
{
theBooks.insert(theBooks.begin()+ mark, pair<int, int>(start, end));
return true;
}
}
};