729. My Calendar I
- 1 minutes read - 488 words題目
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)
想法
這題是很簡單的應用題,只要檢查時段碰撞就好了。
兩種情況,一個是新事件開始比舊事件開始早,另一個是新事件開始比舊事件開始晚或同時。
第一種情況,只需檢查是否整個新事件都在舊事件開始前結束就好。
第二種情況,則檢查是否新事件的開始時間在舊事件區間內。
因為以開始時間區分,所以第一種情況與第二種情況不會同時發生,每次只要測試其中一個。
通過所有測試的話,就把新事件加入事件列表。
實作
Javascript
class MyCalendar {
// Javascript 中被 new 建立時就會呼叫 constructor
constructor() {
this.events = [];
}
// 預約事件的函式
book(start, end) {
// 把已經建立的事件都做一次碰撞測試
for (let i = 0; i < this.events.length; i++) {
let event = this.events[i];
// 如果新事件開始比舊事件開始早,但結束在舊事件開始後,一定會撞到
if (start < event.start && end > event.start) return false;
// 如果新事件開始在舊事件時間範圍內,也一定會撞到
else if (start >= event.start && start < event.end) return false;
}
// 通過所有測試,建立事件
this.events.push({ start, end });
return true;
}
}