Skip to content

Commit 4c7b66d

Browse files
authored
Create Solution.js
1 parent d9c4058 commit 4c7b66d

File tree

1 file changed

+101
-0
lines changed
  • solution/1900-1999/1942.The Number of the Smallest Unoccupied Chair

1 file changed

+101
-0
lines changed
Lines changed: 101 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,101 @@
1+
/**
2+
* @param {number[][]} times
3+
* @param {number} targetFriend
4+
* @return {number}
5+
*/
6+
var smallestChair = function(times, targetFriend) {
7+
const n = times.length;
8+
9+
const availableChairs = new MinHeap();
10+
11+
const busy = new MinHeap((a, b) => a[0] - b[0]);
12+
13+
for (let i = 0; i < n; ++i) {
14+
times[i].push(i);
15+
availableChairs.push(i);
16+
}
17+
18+
times.sort((a, b) => a[0] - b[0]);
19+
20+
for (let t of times) {
21+
const arrival = t[0], leaving = t[1], friendIndex = t[2];
22+
23+
while (!busy.isEmpty() && busy.peek()[0] <= arrival) {
24+
availableChairs.push(busy.pop()[1]);
25+
}
26+
27+
const chair = availableChairs.pop();
28+
29+
if (friendIndex === targetFriend) {
30+
return chair;
31+
}
32+
33+
busy.push([leaving, chair]);
34+
}
35+
36+
return -1;
37+
};
38+
39+
class MinHeap {
40+
constructor(compare = (a, b) => a - b) {
41+
this.heap = [];
42+
this.compare = compare;
43+
}
44+
45+
push(val) {
46+
this.heap.push(val);
47+
this.bubbleUp(this.heap.length - 1);
48+
}
49+
50+
pop() {
51+
const top = this.heap[0];
52+
const bottom = this.heap.pop();
53+
if (this.heap.length > 0) {
54+
this.heap[0] = bottom;
55+
this.bubbleDown(0);
56+
}
57+
return top;
58+
}
59+
60+
peek() {
61+
return this.heap[0];
62+
}
63+
64+
isEmpty() {
65+
return this.heap.length === 0;
66+
}
67+
68+
bubbleUp(index) {
69+
while (index > 0) {
70+
const parentIndex = Math.floor((index - 1) / 2);
71+
if (this.compare(this.heap[index], this.heap[parentIndex]) < 0) {
72+
[this.heap[index], this.heap[parentIndex]] = [this.heap[parentIndex], this.heap[index]];
73+
index = parentIndex;
74+
} else {
75+
break;
76+
}
77+
}
78+
}
79+
80+
bubbleDown(index) {
81+
const length = this.heap.length;
82+
while (true) {
83+
const leftIndex = 2 * index + 1;
84+
const rightIndex = 2 * index + 2;
85+
let smallest = index;
86+
87+
if (leftIndex < length && this.compare(this.heap[leftIndex], this.heap[smallest]) < 0) {
88+
smallest = leftIndex;
89+
}
90+
if (rightIndex < length && this.compare(this.heap[rightIndex], this.heap[smallest]) < 0) {
91+
smallest = rightIndex;
92+
}
93+
if (smallest !== index) {
94+
[this.heap[index], this.heap[smallest]] = [this.heap[smallest], this.heap[index]];
95+
index = smallest;
96+
} else {
97+
break;
98+
}
99+
}
100+
}
101+
}

0 commit comments

Comments
 (0)