Skip to content

Commit fc9b1ef

Browse files
authored
Create 1847-closest-room.js
1 parent e7e7931 commit fc9b1ef

File tree

1 file changed

+71
-0
lines changed

1 file changed

+71
-0
lines changed

1847-closest-room.js

Lines changed: 71 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,71 @@
1+
2+
/**
3+
* @param {number[][]} rooms
4+
* @param {number[][]} queries
5+
* @return {number[]}
6+
*/
7+
const closestRoom = function (rooms, queries) {
8+
rooms.sort((a, b) => b[1] - a[1])
9+
const n = queries.length
10+
const minSize = Array(n).fill(0).map((_, i) => i)
11+
.sort((a, b) => queries[b][1] - queries[a][1])
12+
13+
const res = new Array(queries.length).fill(-1)
14+
const bst = new BinarySearchTree()
15+
let currentRoom = 0
16+
17+
minSize.forEach((query) => {
18+
const [preferredRoom, minimumSize] = queries[query]
19+
if (rooms[0][1] < minimumSize) return
20+
21+
while (currentRoom < rooms.length && rooms[currentRoom][1] >= minimumSize) {
22+
bst.add(rooms[currentRoom][0])
23+
currentRoom++
24+
}
25+
26+
res[query] = bst.search(preferredRoom)
27+
})
28+
29+
return res
30+
}
31+
32+
class BinarySearchTree {
33+
constructor() {
34+
this.root = null
35+
}
36+
37+
add(val) {
38+
this.root = this.insert(this.root, val)
39+
}
40+
41+
insert(node, val) {
42+
if (!node) return new TreeNode(val)
43+
if (node.val < val) {
44+
node.right = this.insert(node.right, val)
45+
} else {
46+
node.left = this.insert(node.left, val)
47+
}
48+
return node
49+
}
50+
51+
search(val, node = this.root) {
52+
if (node.val === val) return val
53+
const currentDistance = Math.abs(node.val - val)
54+
const nextChild = node.val < val ? node.right : node.left
55+
if (!nextChild) return node.val
56+
const closestChild = this.search(val, nextChild)
57+
const childDistance = Math.abs(closestChild - val)
58+
if (childDistance < currentDistance) return closestChild
59+
if (childDistance === currentDistance)
60+
return Math.min(closestChild, node.val)
61+
return node.val
62+
}
63+
}
64+
65+
class TreeNode {
66+
constructor(val) {
67+
this.val = val
68+
this.left = null
69+
this.right = null
70+
}
71+
}

0 commit comments

Comments
 (0)