-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path0855-exam-room.js
More file actions
73 lines (62 loc) · 2 KB
/
0855-exam-room.js
File metadata and controls
73 lines (62 loc) · 2 KB
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
/**
* Exam Room
* Time Complexity: O(N)
* Space Complexity: O(N)
*/
var ExamRoom = function (n) {
this.roomSize = n;
this.seatOccupancy = [];
};
ExamRoom.prototype.seat = function () {
if (this.seatOccupancy.length === 0) {
this.seatOccupancy.push(0);
return 0;
}
let currentMaximumDistance = this.seatOccupancy[0];
let candidateSeatIdentifier = 0;
for (
let iteratorIndex = 1;
iteratorIndex < this.seatOccupancy.length;
iteratorIndex++
) {
const previousOccupiedPosition = this.seatOccupancy[iteratorIndex - 1];
const currentOccupiedPosition = this.seatOccupancy[iteratorIndex];
const distanceBetweenSeats = Math.floor(
(currentOccupiedPosition - previousOccupiedPosition) / 2,
);
if (distanceBetweenSeats > currentMaximumDistance) {
currentMaximumDistance = distanceBetweenSeats;
candidateSeatIdentifier = Math.floor(
(currentOccupiedPosition + previousOccupiedPosition) / 2,
);
}
}
const lastOccupiedPosition =
this.seatOccupancy[this.seatOccupancy.length - 1];
const finalSeatDistance = this.roomSize - 1 - lastOccupiedPosition;
if (finalSeatDistance > currentMaximumDistance) {
candidateSeatIdentifier = this.roomSize - 1;
}
const insertionIndexValue = this.findPositionForInsertion(
candidateSeatIdentifier,
);
this.seatOccupancy.splice(insertionIndexValue, 0, candidateSeatIdentifier);
return candidateSeatIdentifier;
};
ExamRoom.prototype.leave = function (p) {
const removalIndex = this.seatOccupancy.indexOf(p);
this.seatOccupancy.splice(removalIndex, 1);
};
ExamRoom.prototype.findPositionForInsertion = function (valueToInsert) {
let lowPointer = 0;
let highPointer = this.seatOccupancy.length - 1;
while (lowPointer <= highPointer) {
const middlePointer = Math.floor((lowPointer + highPointer) / 2);
if (this.seatOccupancy[middlePointer] < valueToInsert) {
lowPointer = middlePointer + 1;
} else {
highPointer = middlePointer - 1;
}
}
return lowPointer;
};