#855
Exam Room
expert · 1000 · lc medium +32 · 43.2% accepted · 1,417 likes · top 25%
Description
An exam room has n seats in a single row, labeled 0 through n - 1.
A student entering the room sits in the empty seat that maximizes their distance from the nearest occupied seat. If multiple seats tie, the student picks the one with the smallest index. If the room is empty, the student sits at seat 0.
Implement the ExamRoom class:
- ExamRoom(int n) — initializes the room with n seats.
- int seat() — seats the next student and returns the chosen seat label.
- void leave(int p) — marks seat p as vacated. It is guaranteed that seat p is occupied.
Example 1:
Input
["ExamRoom", "seat", "seat", "seat", "seat", "leave", "seat"]
[[10], [], [], [], [], [4], []]
Output
[null, 0, 9, 4, 2, null, 5]
Example 2:
Explanation
ExamRoom examRoom = new ExamRoom(10);
examRoom.seat(); // return 0, no one is in the room, then the student sits at seat number 0.
examRoom.seat(); // return 9, the student sits at the last seat number 9.
examRoom.seat(); // return 4, the student sits at the last seat number 4.
examRoom.seat(); // return 2, the student sits at the last seat number 2.
examRoom.leave(4);
examRoom.seat(); // return 5, the student sits at the last seat number 5.
Code
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16