|
| 1 | +/** |
| 2 | + * 729. My Calendar I |
| 3 | + * https://leetcode.com/problems/my-calendar-i/ |
| 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 double booking. |
| 8 | + * |
| 9 | + * A double booking happens when two events have some non-empty intersection (i.e., some moment |
| 10 | + * is common to both 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 |
| 14 | + * that startTime <= x < endTime. |
| 15 | + * |
| 16 | + * Implement the MyCalendar class: |
| 17 | + * - MyCalendar() Initializes the calendar object. |
| 18 | + * - boolean book(int startTime, int endTime) Returns true if the event can be added to the |
| 19 | + * calendar successfully without causing a double booking. Otherwise, return false and do |
| 20 | + * not add the event to the calendar. |
| 21 | + */ |
| 22 | + |
| 23 | +class MyCalendar { |
| 24 | + constructor() { |
| 25 | + this.events = []; |
| 26 | + } |
| 27 | + |
| 28 | + /** |
| 29 | + * @param {number} startTime |
| 30 | + * @param {number} endTime |
| 31 | + * @returns {boolean} |
| 32 | + */ |
| 33 | + book(startTime, endTime) { |
| 34 | + const event = [startTime, endTime]; |
| 35 | + const index = this.findInsertIndex(startTime); |
| 36 | + |
| 37 | + if (this.overlapsPrevious(index - 1, startTime) || this.overlapsNext(index, endTime)) { |
| 38 | + return false; |
| 39 | + } |
| 40 | + |
| 41 | + this.events.splice(index, 0, event); |
| 42 | + return true; |
| 43 | + } |
| 44 | + |
| 45 | + /** |
| 46 | + * @param {number} startTime |
| 47 | + * @returns {number} |
| 48 | + */ |
| 49 | + findInsertIndex(startTime) { |
| 50 | + let left = 0; |
| 51 | + let right = this.events.length; |
| 52 | + |
| 53 | + while (left < right) { |
| 54 | + const mid = Math.floor((left + right) / 2); |
| 55 | + if (this.events[mid][0] > startTime) { |
| 56 | + right = mid; |
| 57 | + } else { |
| 58 | + left = mid + 1; |
| 59 | + } |
| 60 | + } |
| 61 | + |
| 62 | + return left; |
| 63 | + } |
| 64 | + |
| 65 | + /** |
| 66 | + * @param {number} prevIndex |
| 67 | + * @param {number} startTime |
| 68 | + * @returns {boolean} |
| 69 | + */ |
| 70 | + overlapsPrevious(prevIndex, startTime) { |
| 71 | + return prevIndex >= 0 && this.events[prevIndex][1] > startTime; |
| 72 | + } |
| 73 | + |
| 74 | + /** |
| 75 | + * @param {number} nextIndex |
| 76 | + * @param {number} endTime |
| 77 | + * @returns {boolean} |
| 78 | + */ |
| 79 | + overlapsNext(nextIndex, endTime) { |
| 80 | + return nextIndex < this.events.length && this.events[nextIndex][0] < endTime; |
| 81 | + } |
| 82 | +} |
0 commit comments