-
Notifications
You must be signed in to change notification settings - Fork 13
/
solution.cpp
61 lines (50 loc) · 1.93 KB
/
solution.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
#include <vector>
#include <queue>
#include <algorithm>
class Solution
{
public:
int smallestChair(std::vector<std::vector<int>> ×, int targetFriend)
{
int n = times.size();
// Create a list of arrivals with friend index for tracking
std::vector<std::pair<int, int>> arrivals;
for (int i = 0; i < n; ++i)
{
arrivals.push_back({times[i][0], i});
}
// Sort friends based on their arrival time
std::sort(arrivals.begin(), arrivals.end());
// Min-Heap to track available chairs
std::priority_queue<int, std::vector<int>, std::greater<int>> availableChairs;
for (int i = 0; i < n; ++i)
{
availableChairs.push(i); // All chairs start as available
}
// Priority queue to track when chairs are freed
std::priority_queue<std::pair<int, int>, std::vector<std::pair<int, int>>, std::greater<std::pair<int, int>>> leavingQueue;
// Iterate through each friend based on arrival
for (auto &arrival : arrivals)
{
int arrivalTime = arrival.first;
int friendIndex = arrival.second;
// Free chairs that are vacated before the current arrival time
while (!leavingQueue.empty() && leavingQueue.top().first <= arrivalTime)
{
availableChairs.push(leavingQueue.top().second);
leavingQueue.pop();
}
// Assign the smallest available chair
int chair = availableChairs.top();
availableChairs.pop();
// If this is the target friend, return their chair number
if (friendIndex == targetFriend)
{
return chair;
}
// Mark the chair as being used until the friend's leave time
leavingQueue.push({times[friendIndex][1], chair});
}
return -1; // Should never reach here
}
};