forked from liuyubobobo/Play-Leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.cpp
75 lines (59 loc) · 1.45 KB
/
main.cpp
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
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
/// Source : https://leetcode.com/problems/exam-room/description/
/// Author : liuyubobobo
/// Time : 2018-06-17
#include <iostream>
#include <set>
using namespace std;
/// Using TreeSet
///
/// Time Complexity: seat - O(N)
/// leave - O(logN)
/// Space Compexity: O(N)
class ExamRoom {
private:
set<int> seats;
int N;
public:
ExamRoom(int N) {
this->N = N;
seats.clear();
}
int seat() {
if(seats.empty()){
seats.insert(0);
return 0;
}
int maxDis = *seats.begin();
int res = 0;
set<int>::iterator last_iter = seats.begin();
set<int>::iterator iter = seats.begin();
iter ++;
for(; iter != seats.end() ; last_iter++, iter ++){
int dis = (*iter - *last_iter) / 2;
if(dis > maxDis){
maxDis = dis;
res = *last_iter + dis;
}
}
if(N - 1 - *last_iter > maxDis){
maxDis = N - 1 - *last_iter;
res = N - 1;
}
seats.insert(res);
return res;
}
void leave(int p) {
seats.erase(p);
}
};
int main() {
int N = 10;
ExamRoom examRoom(N);
cout << examRoom.seat() << endl; // 0
cout << examRoom.seat() << endl; // 9
cout << examRoom.seat() << endl; // 4
cout << examRoom.seat() << endl; // 2
examRoom.leave(4);
cout << examRoom.seat() << endl; // 5
return 0;
}