Problem
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 <= N <= 10^9
ExamRoom.seat()
Ā andĀExamRoom.leave()
Ā will be called at mostĀ10^4
Ā times across all test cases.- Calls toĀ
ExamRoom.leave(p)
Ā are guaranteed to have a student currently sitting in seat numberĀp
.
Solution: BST
Use a BST (ordered set) to track the current seatings.
Time Complexity:
init: O(1)
seat: O(P)
leave: O(logP)
Space complexity: O(P)
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 |
// Author: Huahua // Running time: 24 ms class ExamRoom { public: ExamRoom(int N): N_(N) {} int seat() { int p = 0; int max_dist = s_.empty() ? 0 : *s_.begin(); auto left = s_.begin(); auto right = left; while (left != s_.end()) { ++right; int l = *left; int r = right != s_.end() ? *right : (2 * (N_ - 1) - *left); int d = (r - l) / 2; if (d > max_dist) { max_dist = d; p = l + d; } left = right; } s_.insert(p); return p; } void leave(int p) { s_.erase(p); } private: const int N_; set<int> s_; }; |