- Exam Room
Medium
There is an exam room with n seats in a single row labeled from 0 to 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. If no one is in the room, then the student sits at seat number 0.
Design a class that simulates the mentioned exam room.
Implement the ExamRoom class:
ExamRoom(int n) Initializes the object of the exam room with the number of the seats n.
int seat() Returns the label of the seat at which the next student will set.
void leave(int p) Indicates that the student sitting at seat p will leave the room. It is guaranteed that there will be a student sitting at seat p.
Example 1:
Input
[“ExamRoom”, “seat”, “seat”, “seat”, “seat”, “leave”, “seat”]
[[10], [], [], [], [], [4], []]
Output
[null, 0, 9, 4, 2, null, 5]
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.
Constraints:
1 <= n <= 109
It is guaranteed that there is a student sitting at seat p.
At most 104 calls will be made to seat and leave.
这道题思路不难。下面两个帖子都有很好的解释。但调通并且不超时也不容易。
https://www.cnblogs.com/grandyang/p/10618437.html
https://labuladong.github.io/algo/di-san-zha-24031/jing-dian–a94a0/ru-he-diao-7b69a/
解法1:类似grandyang的解法。每次来新人时,要遍历set中的所有元素。所以每次时间复杂度是O(n)。n是已有的被占用的位置总和。
class ExamRoom {
public:
ExamRoom(int N) : n(N) {
}
int seat() {
int oldSlot = -1, maxDist = 0, pos = 0;
for (auto spot : spots) {
if (oldSlot == -1) {
if (maxDist < spot) {
maxDist = spot;
pos = 0;
}
} else {
if (maxDist < (spot - oldSlot) / 2) {
maxDist = (spot - oldSlot) / 2;
pos = oldSlot + maxDist;
}
}
oldSlot = spot;
}
if (oldSlot >= 0 && maxDist < n - 1 - oldSlot) {
maxDist = n - 1 - oldSlot;
pos = n - 1;
}
spots.insert(pos);
return pos;
}
void leave(int p) {
spots.erase(p);
}
private:
int n;
set<int> spots;
};
解法2:用labuladong的解法。维护一个minHeap。每次用O(log(n))的时间就可以找到最合适的位置。下次做。
https://labuladong.github.io/algo/di-san-zha-24031/jing-dian–a94a0/ru-he-diao-7b69a/
3695



被折叠的 条评论
为什么被折叠?



