| | 1 | | // -------------------------------------------------------------------------------- |
| | 2 | | // Copyright (C) 2025 Eugene Eremeev (also known as Yevhenii Yeriemeieiv). |
| | 3 | | // All Rights Reserved. |
| | 4 | | // -------------------------------------------------------------------------------- |
| | 5 | | // This software is the confidential and proprietary information of Eugene Eremeev |
| | 6 | | // (also known as Yevhenii Yeriemeieiv) ("Confidential Information"). You shall not |
| | 7 | | // disclose such Confidential Information and shall use it only in accordance with |
| | 8 | | // the terms of the license agreement you entered into with Eugene Eremeev (also |
| | 9 | | // known as Yevhenii Yeriemeieiv). |
| | 10 | | // -------------------------------------------------------------------------------- |
| | 11 | |
|
| | 12 | | namespace LeetCode.Algorithms.MyCalendar1; |
| | 13 | |
|
| | 14 | | /// <inheritdoc /> |
| | 15 | | public class MyCalendar1BinarySearch : IMyCalendar1 |
| | 16 | | { |
| 1 | 17 | | private readonly List<Item> _items = []; |
| | 18 | |
|
| | 19 | | /// <summary> |
| | 20 | | /// Time complexity - O(n) |
| | 21 | | /// Space complexity - O(n) |
| | 22 | | /// </summary> |
| | 23 | | /// <param name="start"></param> |
| | 24 | | /// <param name="end"></param> |
| | 25 | | /// <returns></returns> |
| | 26 | | public bool Book(int start, int end) |
| 3 | 27 | | { |
| 3 | 28 | | var item = new Item(start, end); |
| | 29 | |
|
| 3 | 30 | | var index = _items.BinarySearch(item); |
| | 31 | |
|
| 3 | 32 | | if (index < 0) |
| 3 | 33 | | { |
| 3 | 34 | | index = ~index; |
| 3 | 35 | | } |
| | 36 | |
|
| 3 | 37 | | if ((index < _items.Count && _items[index].Start < end) || (index > 0 && _items[index - 1].End > start)) |
| 1 | 38 | | { |
| 1 | 39 | | return false; |
| | 40 | | } |
| | 41 | |
|
| 2 | 42 | | _items.Insert(index, item); |
| | 43 | |
|
| 2 | 44 | | return true; |
| 3 | 45 | | } |
| | 46 | |
|
| 3 | 47 | | private class Item(int start, int end) : IComparable<Item> |
| | 48 | | { |
| 7 | 49 | | public int Start { get; } = start; |
| 5 | 50 | | public int End { get; } = end; |
| | 51 | |
|
| | 52 | | public int CompareTo(Item? other) |
| 2 | 53 | | { |
| 2 | 54 | | if (other == null) |
| 0 | 55 | | { |
| 0 | 56 | | return -1; |
| | 57 | | } |
| | 58 | |
|
| 2 | 59 | | return Start.CompareTo(other.Start); |
| 2 | 60 | | } |
| | 61 | | } |
| | 62 | | } |