Skip to content

Commit c8ec970

Browse files
authored
Update 218-the-skyline-problem.js
1 parent e8c54c1 commit c8ec970

File tree

1 file changed

+43
-0
lines changed

1 file changed

+43
-0
lines changed

218-the-skyline-problem.js

+43
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,46 @@
1+
/**
2+
* @param {number[][]} buildings
3+
* @return {number[][]}
4+
*/
5+
var getSkyline = function(buildings) {
6+
const edgeSet = new Set();
7+
for (let i = 0; i < buildings.length; i++) {
8+
const [from, to] = buildings[i];
9+
edgeSet.add(from);
10+
edgeSet.add(to);
11+
}
12+
const positions = [...edgeSet];
13+
positions.sort((a, b) => a - b);
14+
15+
const pq = new PriorityQueue({compare: (a, b) => b[2] - a[2]});
16+
17+
const result = [];
18+
19+
let j = 0;
20+
for (let i = 0; i < positions.length; i++) {
21+
const position = positions[i];
22+
23+
for (j; j < buildings.length && buildings[j][0] <= position; j++) {
24+
pq.enqueue(buildings[j]);
25+
}
26+
27+
while (!pq.isEmpty() && pq.front()[1] <= position) {
28+
pq.dequeue();
29+
}
30+
31+
let maxHeight = pq.front()?.[2] ?? 0;
32+
33+
if (!result.length || result.at(-1)[1] !== maxHeight) {
34+
result.push([position, maxHeight]);
35+
}
36+
}
37+
38+
return result;
39+
};
40+
41+
// another
42+
43+
144
/**
245
* @param {number[][]} buildings
346
* @return {number[][]}

0 commit comments

Comments
 (0)