|
| 1 | +/** |
| 2 | + * 731. My Calendar II |
| 3 | + * https://leetcode.com/problems/my-calendar-ii/ |
| 4 | + * Difficulty: Medium |
| 5 | + * |
| 6 | + * You are implementing a program to use as your calendar. We can add a new event if adding the |
| 7 | + * event will not cause a triple booking. |
| 8 | + * |
| 9 | + * A triple booking happens when three events have some non-empty intersection (i.e., some moment |
| 10 | + * is common to all the three events.). |
| 11 | + * |
| 12 | + * The event can be represented as a pair of integers startTime and endTime that represents a |
| 13 | + * booking on the half-open interval [startTime, endTime), the range of real numbers x such that |
| 14 | + * startTime <= x < endTime. |
| 15 | + * |
| 16 | + * Implement the MyCalendarTwo class: |
| 17 | + * - MyCalendarTwo() Initializes the calendar object. |
| 18 | + * - boolean book(int startTime, int endTime) Returns true if the event can be added to the calendar |
| 19 | + * successfully without causing a triple booking. Otherwise, return false and do not add the event |
| 20 | + * to the calendar. |
| 21 | + */ |
| 22 | + |
| 23 | +var MyCalendarTwo = function() { |
| 24 | + this.bookings = []; |
| 25 | + this.overlaps = []; |
| 26 | +}; |
| 27 | + |
| 28 | +/** |
| 29 | + * @param {number} startTime |
| 30 | + * @param {number} endTime |
| 31 | + * @return {boolean} |
| 32 | + */ |
| 33 | +MyCalendarTwo.prototype.book = function(startTime, endTime) { |
| 34 | + for (const [start, end] of this.overlaps) { |
| 35 | + if (startTime < end && endTime > start) return false; |
| 36 | + } |
| 37 | + |
| 38 | + for (const [start, end] of this.bookings) { |
| 39 | + if (startTime < end && endTime > start) { |
| 40 | + this.overlaps.push([Math.max(start, startTime), Math.min(end, endTime)]); |
| 41 | + } |
| 42 | + } |
| 43 | + |
| 44 | + this.bookings.push([startTime, endTime]); |
| 45 | + return true; |
| 46 | +}; |
0 commit comments