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 and end that represents a booking on the half-open interval [start, end), the range of real numbers x such that start <= x < end.
Implement the MyCalendar class:
MyCalendar() Initializes the calendar object.
boolean book(int start, int end) Returns 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.
Example 1:
Input
[“MyCalendar”, “book”, “book”, “book”]
[[], [10, 20], [15, 25], [20, 30]]
Output
[null, true, false, true]
Explanation
MyCalendar myCalendar = new MyCalendar();
myCalendar.book(10, 20); // return True
myCalendar.book(15, 25); // return False, It can not be booked because time 15 is already booked by another event.
myCalendar.book(20, 30); // return True, The event can be booked, as the first event takes every time less than 20, but not including 20.
每段[start, end)表示日程是从start~end(不包含end), 日程不能有重叠的部分,
如果能加入日程,返回true, 否则false.
主要是判断每一段是否与已有的日程有重叠,
新进来的日程可以跟已有的每一段比较,
两段日程(s1, e1), (s2, e2)有重叠表示要么s2在s1 ~ e1之间,要么e2在s1 ~ e1之间。
没有重叠的话把新的日程加进去,返回true。
class MyCalendar {
List<Pair<Integer, Integer>> calendar;
public MyCalendar() {
calendar = new ArrayList<>();
}
public boolean book(int start, int end) {
for(Pair<Integer, Integer> tmp : calendar) {
if(end > tmp.getKey() && start < tmp.getValue()) {
return false;
}
}
calendar.add(new Pair(start, end));
return true;
}
}
还有一种beat 99%的方法,
构造一个类似双向链表的数据结构,每个节点是一个日程(start, end)
当没有重叠时:即s1 >= e1 或者 e2 <= s1时
要插入新的节点,通过移动链表的指针进行插入操作。
如果有重叠,直接返回false。
class MyCalendar {
private class CalendarNode{
int start;
int end;
CalendarNode next;
CalendarNode prev;
public CalendarNode(int start, int end){
this.start = start;
this.end = end;
}
}
CalendarNode calendar;
public MyCalendar() {
calendar = null;
}
public boolean book(int start, int end) {
if (calendar == null) {
calendar = new CalendarNode(start, end);
return true;
} else {
return insertNewCalendarNode(start, end);
}
}
private boolean insertNewCalendarNode(int start, int end){
CalendarNode cn = calendar;
//没有重叠的情况
while (end <= cn.start || start >= cn.end) {
if (cn.start >= end) {
if (cn.prev != null) {
cn = cn.prev;
} else {
cn.prev = new CalendarNode(start, end);
return true;
}
} else if (cn.end <= start) {
if (cn.next != null) {
cn = cn.next;
} else {
cn.next = new CalendarNode(start, end);
return true;
}
}
}
return false;
}
}