-
Notifications
You must be signed in to change notification settings - Fork 886
/
ExamRoom.swift
51 lines (42 loc) · 1.12 KB
/
ExamRoom.swift
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
/**
* Question Link: https://leetcode.com/problems/exam-room/
* Primary idea: Calculate and compare middle point between two taken seats.
*
* Time Complexity: O(n) for seat(), O(1) for leave(at:), Space Complexity: O(n)
*
*/
class ExamRoom {
var seats: [Int]
init(_ n: Int) {
seats = Array(repeating: 0, count: n)
}
func seat() -> Int {
var maxDistance = 0, maxIndex = 0, lastOne = -1
for (i, seat) in seats.enumerated() {
if seat == 1 {
if lastOne == -1 {
if maxDistance < i {
maxDistance = i
maxIndex = 0
}
} else {
if maxDistance < (i - lastOne) / 2 {
maxDistance = (i - lastOne) / 2
maxIndex = lastOne + (i - lastOne) / 2
}
}
}
lastOne = i
}
if lastOne != -1 {
if maxDistance < (seats.count - 1 - lastOne) / 2 {
maxIndex = seats.count - 1
}
}
seats[maxIndex] = 1
return maxIndex
}
func leave(_ seat: Int) {
seats[seat] = 0
}
}