855 Exam Room
855. Exam Room
1. Question
In an exam room, there areN
seats in a single row, numbered0, 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 classExamRoom(int N)
that exposes two functions:ExamRoom.seat()
returning anint
representing what seat the student sat in, andExamRoom.leave(int p)
representing that the student in seat numberp
now leaves the room. It is guaranteed that any calls toExamRoom.leave(p)
have a student sitting in seatp
.
Example 1:
Note:
1 <= N <= 10^9
ExamRoom.seat()
andExamRoom.leave()
will be called at most10^4
times across all test cases.Calls to
ExamRoom.leave(p)
are guaranteed to have a student currently sitting in seat numberp
.
2. Implementation
(1) Heap
思路: 用maxHeap保留区间,按照区间距离从大到小排序。call Leave()时,则需要遍历heap找出包含p点的左区间和右区间,将这两个区间删除,并将左区间的最左点和右区间的最右点合并成一个新区间
3. Time & Space Complexity
Heap:时间复杂度seat(): O(logN), leave(): O(N), 空间复杂度O(N)
Last updated
Was this helpful?