Exam Room LeetCode solution in C++

1
class ExamRoom {
2
public:
3
set<int> s; // ordered set
4
int num;
5
ExamRoom(int n) {
6
num = n; // total seats
7
}
8

9
int seat() {
10
if (s.size() == 0) {
11
s.insert(0);
12
return 0;
13
} // if size is zero place at seat 0
14
auto itr = s.begin();
15
if (s.size() == 1) { // if size==1 -> check if its closer to 0 or last seat (num-1)
16
if (*itr > num - 1 - (*itr)) {
17
s.insert(0);
18
return 0;
19
} else {
20
s.insert(num - 1);
21
return num - 1;
22
}
23
}
24
int mx = -1; // for max gap
25
int l = 0; // for left index of the student to max gap.
26

27
if (s.find(0) == s.end()) {
28
mx = (*itr);
29
l = -mx;
30
} // if 0 is not seated -> check gap with 0 and starting seat.
31

32
// Iterate the set to calculate gaps
33
for (int i = 0; i < s.size() - 1; i++) {
34
int a = *itr; // seat number for 1st element
35
itr++;
36
int b = *itr; // seat number of next element in the set
37

38
// check the gap and update
39
if (mx < (b - a) / 2) {
40
mx = (b - a) / 2;
41
l = a;
42
}
43
}
44
if (s.find(num - 1) == s.end()) { // if last seat is vacant -> check gap
45
// with last filled seat and (num-1)
46
if (mx < num - 1 - (*itr)) {
47
mx = (num - 1 - (*itr));
48
l = *itr;
49
}
50
}
51
s.insert(l + mx); // place the student at l+mx
52
return l + mx;
53
}
54

55
void leave(int p) {
56
// remove student from set
57
s.erase(p);
58
}
59
};

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0