Skip to content

Commit 81d3a3e

Browse files
authored
Create 2940-find-building-where-alice-and-bob-can-meet.js
1 parent 62375ef commit 81d3a3e

File tree

1 file changed

+56
-0
lines changed

1 file changed

+56
-0
lines changed
Lines changed: 56 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,56 @@
1+
/**
2+
* @param {number[]} heights
3+
* @param {number[][]} queries
4+
* @return {number[]}
5+
*/
6+
var leftmostBuildingQueries = function (heights, queries) {
7+
const st = []
8+
const [hs, qs] = [heights, queries]
9+
let n = qs.length;
10+
let ans = new Array(n).fill(-1);
11+
let es = new Array(hs.length).fill().map(() => []);
12+
for (let i = 0; i < n; i++) {
13+
let x = qs[i][0];
14+
let y = qs[i][1];
15+
if (x > y) {
16+
[x, y] = [y, x];
17+
}
18+
if (hs[y] > hs[x] || x === y) {
19+
ans[i] = y;
20+
} else {
21+
es[y].push([hs[x], i]);
22+
}
23+
}
24+
25+
for (let i = hs.length - 1; i >= 0; i--) {
26+
let n1 = st.length;
27+
for (let [x, y] of es[i]) {
28+
let p = search(x);
29+
if (p < n1 && p >= 0) {
30+
ans[y] = st[p][1];
31+
}
32+
}
33+
while (st.length > 0 && st[st.length - 1][0] <= hs[i]) {
34+
st.pop();
35+
}
36+
st.push([hs[i], i]);
37+
}
38+
return ans;
39+
40+
41+
function search(x) {
42+
let l = 0;
43+
let r = st.length - 1;
44+
let ans = -1;
45+
while (l <= r) {
46+
let m = Math.floor((l + r) / 2);
47+
if (st[m][0] > x) {
48+
ans = Math.max(ans, m);
49+
l = m + 1;
50+
} else {
51+
r = m - 1;
52+
}
53+
}
54+
return ans;
55+
}
56+
}

0 commit comments

Comments
 (0)