| | 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.TheNumberOfTheSmallestUnoccupiedChair; |
| | 13 | |
|
| | 14 | | /// <inheritdoc /> |
| | 15 | | public class TheNumberOfTheSmallestUnoccupiedChairPriorityQueue : ITheNumberOfTheSmallestUnoccupiedChair |
| | 16 | | { |
| | 17 | | /// <summary> |
| | 18 | | /// Time complexity - O(n log n) |
| | 19 | | /// Space complexity - O(n) |
| | 20 | | /// </summary> |
| | 21 | | /// <param name="times"></param> |
| | 22 | | /// <param name="targetFriend"></param> |
| | 23 | | /// <returns></returns> |
| | 24 | | public int SmallestChair(int[][] times, int targetFriend) |
| 4 | 25 | | { |
| 4 | 26 | | var targetFriendArrival = times[targetFriend][0]; |
| | 27 | |
|
| 70 | 28 | | Array.Sort(times, (a, b) => a[0] - b[0]); |
| | 29 | |
|
| 4 | 30 | | var availablePriorityQueue = new PriorityQueue<int, int>(); |
| 4 | 31 | | var occupiedPriorityQueue = new PriorityQueue<(int Chair, int Leaving), int>(); |
| | 32 | |
|
| 4 | 33 | | var currentChair = 0; |
| | 34 | |
|
| 58 | 35 | | foreach (var time in times) |
| 25 | 36 | | { |
| 25 | 37 | | var arrival = time[0]; |
| 25 | 38 | | var leaving = time[1]; |
| | 39 | |
|
| 36 | 40 | | while (occupiedPriorityQueue.Count > 0 && occupiedPriorityQueue.Peek().Leaving <= arrival) |
| 11 | 41 | | { |
| 11 | 42 | | var availableChair = occupiedPriorityQueue.Dequeue().Chair; |
| | 43 | |
|
| 11 | 44 | | availablePriorityQueue.Enqueue(availableChair, availableChair); |
| 11 | 45 | | } |
| | 46 | |
|
| 25 | 47 | | var nextChair = availablePriorityQueue.Count == 0 ? currentChair++ : availablePriorityQueue.Dequeue(); |
| | 48 | |
|
| 25 | 49 | | if (arrival == targetFriendArrival) |
| 4 | 50 | | { |
| 4 | 51 | | return nextChair; |
| | 52 | | } |
| | 53 | |
|
| 21 | 54 | | occupiedPriorityQueue.Enqueue((nextChair, leaving), leaving); |
| 21 | 55 | | } |
| | 56 | |
|
| 0 | 57 | | return -1; |
| 4 | 58 | | } |
| | 59 | | } |