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§ have a student sitting in seat p.
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§ are guaranteed to have a student currently sitting in seat number 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.
解答1
第一种方法用一个vector来存储就座人的座位号,每次就座的时候,遍历数组找到最大的座位间隔,然后在这个间隔的中间位置就座。
离座的时候只需从vector中删除这个座位号即可。这个算法复杂度为线性的。
代码1
class ExamRoom {
int num = 0;
vector<int > row;
public:
ExamRoom(int N) {
num = N;
}
int seat() {
if (row.size() == 0) {
row.push_back(0);
return 0;
}
int d = max(row[0], num - 1 - row[row.size() - 1]);
for (int i = 1;i < row.size(); i ++) {
d = max(d, (row[i] - row[i -