Skip to content

Instantly share code, notes, and snippets.

@ko-lem
Created December 26, 2018 15:15
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ko-lem/ec2475b2cbaa4a14e40e541dc7c04e2c to your computer and use it in GitHub Desktop.
Save ko-lem/ec2475b2cbaa4a14e40e541dc7c04e2c to your computer and use it in GitHub Desktop.
/**
* @param {number[][]} buildings
* @return {number[][]}
*/
var getSkyline = function(buildings) {
var edges = calcSortedEdges(buildings);
var skyline = [];
var heights = new SlowPriorityQueue();
var currHeight = 0;
heights.add(0);
for (var edge of edges) {
if (edge.isStart) {
heights.add(edge.y);
} else {
heights.remove(edge.y);
}
var maxHeight = heights.max();
if (currHeight != maxHeight) {
currHeight = maxHeight;
skyline.push([edge.x, currHeight]);
}
}
return skyline;
};
function calcSortedEdges(buildings) {
var edges = [];
for (var building of buildings) {
edges.push({
x: building[0],
y: building[2],
isStart: true
})
edges.push({
x: building[1],
y: building[2],
isStart: false
})
}
edges.sort(compareEdges);
return edges;
}
function compareEdges(a, b) {
if (a.x === b.x) {
return compareEdgesTiebreak(a, b);
} else {
return a.x - b.x;
}
}
function compareEdgesTiebreak(a, b) {
if (a.isStart && b.isStart) {
return b.y - a.y;
} else if (!a.isStart && !b.isStart) {
return a.y - b.y;
} else if ( a.isStart && !b.isStart) {
return -1;
} else {
return 1;
}
}
// Replace with a proper PriorityQueue implementation
// if faster solution is desired
class SlowPriorityQueue {
constructor() {
this.list = [];
}
add(x) {
this.list.push(x);
}
remove(x) {
var i = this.list.indexOf(x);
this.list.splice(i, 1);
}
max() {
return Math.max(...this.list);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment