-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathexamRoom.cpp
More file actions
75 lines (61 loc) · 1.24 KB
/
examRoom.cpp
File metadata and controls
75 lines (61 loc) · 1.24 KB
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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
#include <iostream>
#include <vector>
// https://leetcode.com/problems/exam-room/
class ExamRoom
{
public:
int total;
std::vector<int> students;
ExamRoom(int n)
{
total = n;
}
int seat()
{
int length = students.size();
if (length == 0)
{
students.push_back(0);
return 0;
}
int prePos = -1, maxDist = students[0], seat = 0;
for (int i = 0; i < length; i += 1)
{
int curPos = students[i];
if (prePos > -1)
{
int tempDist = (curPos - prePos) / 2;
if (tempDist > maxDist)
{
maxDist = tempDist;
seat = prePos + tempDist;
}
}
prePos = curPos;
}
int lastPos = students[length - 1];
if (total - 1 - lastPos > maxDist)
{
seat = total - 1;
}
int insertIndex = 0;
while (
insertIndex < length && students[insertIndex] < seat)
{
insertIndex += 1;
}
students.insert(students.begin() + insertIndex, seat);
return seat;
}
void leave(int p)
{
int length = students.size();
int leaveIndex = 0;
while (
leaveIndex < length && students[leaveIndex] != p)
{
leaveIndex += 1;
}
students.erase(students.begin() + leaveIndex);
}
};