[LeetCode] The Number of the Smallest Unoccupied Chair

1942. The Number of the Smallest Unoccupied Chair

There is a party where n friends numbered from 0 to n - 1 are attending. There is an infinite number of chairs in this party that are numbered from 0 to infinity. When a friend arrives at the party, they sit on the unoccupied chair with the smallest number.

  • For example, if chairs 0, 1, and 5 are occupied when a friend comes, they will sit on chair number 2.

When a friend leaves the party, their chair becomes unoccupied at the moment they leave. If another friend arrives at that same moment, they can sit in that chair.

You are given a 0-indexed 2D integer array times where times[i] = [arrivali, leavingi], indicating the arrival and leaving times of the ith friend respectively, and an integer targetFriend. All arrival times are distinct.

Return the chair number that the friend numbered targetFriend will sit on.

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
class Solution {
public:
int smallestChair(vector<vector<int>>& times, int targetFriend) {
set<int> chair;
priority_queue<pair<int, int>, vector<pair<int, int>>, greater<pair<int, int>>> aq, rq;
for(auto& time : times) {
if(time[0] <= times[targetFriend][0]) {
aq.push({time[0], time[1]});
chair.insert(chair.size());
}
}
while(!aq.empty()) {
if(!rq.empty() && rq.top().first <= aq.top().first) {
chair.insert(rq.top().second);
rq.pop();
} else {
auto a = aq.top();
aq.pop();
if(aq.empty()) return *chair.begin();
rq.push({a.second, *chair.begin()});
chair.erase(chair.begin());
}
}
return -1;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/01/15/PS/LeetCode/the-number-of-the-smallest-unoccupied-chair/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.