Created
December 26, 2018 15:15
-
-
Save ko-lem/ec2475b2cbaa4a14e40e541dc7c04e2c to your computer and use it in GitHub Desktop.
my solution to https://leetcode.com/problems/the-skyline-problem
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* @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