# 855. Exam Room

In an exam room, there are `N` seats in a single row, numbered `0, 1, 2, ..., N-1`.

When a student enters the room, they must sit in the seat that maximizes the distance to the closest person.  If there are multiple such seats, they sit in the seat with the lowest number.  (Also, if no one is in the room, then the student sits at seat number 0.)

Return a class `ExamRoom(int N)` that exposes two functions: `ExamRoom.seat()` returning an `int` representing what seat the student sat in, and `ExamRoom.leave(int p)` representing that the student in seat number `p` now leaves the room.  It is guaranteed that any calls to `ExamRoom.leave(p)` have a student sitting in seat `p`.

Example 1:

``````Input: ["ExamRoom","seat","seat","seat","seat","leave","seat"], [[10],[],[],[],[],[4],[]]
Output: [null,0,9,4,2,null,5]
Explanation:
ExamRoom(10) -> null
seat() -> 0, no one is in the room, then the student sits at seat number 0.
seat() -> 9, the student sits at the last seat number 9.
seat() -> 4, the student sits at the last seat number 4.
seat() -> 2, the student sits at the last seat number 2.
leave(4) -> null
seat() -> 5, the student sits at the last seat number 5.
``````

​​​​​​​

Note:

1. `1 <= N <= 10^9`
2. `ExamRoom.seat()` and `ExamRoom.leave()` will be called at most `10^4` times across all test cases.
3. Calls to `ExamRoom.leave(p)` are guaranteed to have a student currently sitting in seat number `p`.

``````class ExamRoom {
public:
ExamRoom(int N) {
n = N;
}

int seat() {
int start = 0, mx = 0, idx = 0;
for (int i : spots) {
if (start == 0) {
if (mx < i - start) {
mx = i - start;
idx = 0;
}
} else {
if (mx < (i - start + 1) / 2) {
mx = (i - start + 1) / 2;
idx = start + mx - 1;
}
}
start = i + 1;
}
if (start > 0 && mx < n - start) {
mx = n - start;
idx = n - 1;
}
spots.insert(idx);
return idx;
}

void leave(int p) {
spots.erase(p);
}

private:
int n;
set<int> spots;
};
``````

Github 同步地址:

https://github.com/grandyang/leetcode/issues/855

Maximize Distance to Closest Person

https://leetcode.com/problems/exam-room/

https://leetcode.com/problems/exam-room/discuss/139862/C%2B%2BJavaPython-Straight-Forward

https://leetcode.com/problems/exam-room/discuss/148595/Java-PriorityQueue-with-customized-object.-seat%3A-O(logn)-leave-O(n)-with-explanation

 微信打赏 Venmo 打赏
（欢迎加入博主的知识星球，博主将及时答疑解惑，并分享刷题经验与总结，试运营期间前五十位可享受半价优惠～）

×

Help us with donation