|
| 1 | +/** |
| 2 | + * 218. The Skyline Problem |
| 3 | + * https://leetcode.com/problems/the-skyline-problem/ |
| 4 | + * Difficulty: Hard |
| 5 | + * |
| 6 | + * A city's skyline is the outer contour of the silhouette formed by all the buildings in that |
| 7 | + * city when viewed from a distance. Given the locations and heights of all the buildings, |
| 8 | + * return the skyline formed by these buildings collectively. |
| 9 | + * |
| 10 | + * The geometric information of each building is given in the array buildings where |
| 11 | + * buildings[i] = [lefti, righti, heighti]: |
| 12 | + * - lefti is the x coordinate of the left edge of the ith building. |
| 13 | + * - righti is the x coordinate of the right edge of the ith building. |
| 14 | + * - heighti is the height of the ith building. |
| 15 | + * |
| 16 | + * You may assume all buildings are perfect rectangles grounded on an absolutely flat surface |
| 17 | + * at height 0. |
| 18 | + * |
| 19 | + * The skyline should be represented as a list of "key points" sorted by their x-coordinate |
| 20 | + * in the form [[x1,y1],[x2,y2],...]. Each key point is the left endpoint of some horizontal |
| 21 | + * segment in the skyline except the last point in the list, which always has a y-coordinate |
| 22 | + * 0 and is used to mark the skyline's termination where the rightmost building ends. Any ground |
| 23 | + * between the leftmost and rightmost buildings should be part of the skyline's contour. |
| 24 | + * |
| 25 | + * Note: There must be no consecutive horizontal lines of equal height in the output skyline. |
| 26 | + * For instance, [...,[2 3],[4 5],[7 5],[11 5],[12 7],...] is not acceptable; the three lines |
| 27 | + * of height 5 should be merged into one in the final output as such: [...,[2 3],[4 5],[12 7],...] |
| 28 | + */ |
| 29 | + |
| 30 | +/** |
| 31 | + * @param {number[][]} buildings |
| 32 | + * @return {number[][]} |
| 33 | + */ |
| 34 | +var getSkyline = function(buildings) { |
| 35 | + const result = []; |
| 36 | + const events = buildings.flatMap(([l, r, h]) => [[l, -h], [r, h]]); |
| 37 | + |
| 38 | + events.sort((a, b) => a[0] - b[0] || a[1] - b[1]); |
| 39 | + |
| 40 | + for (let i = 0, previous = 0, heights = [0]; i < events.length; i++) { |
| 41 | + const [x, h] = events[i]; |
| 42 | + if (h < 0) { |
| 43 | + heights.push(-h); |
| 44 | + } else { |
| 45 | + heights.splice(heights.indexOf(h), 1); |
| 46 | + } |
| 47 | + const value = Math.max(...heights); |
| 48 | + if (value !== previous) { |
| 49 | + result.push([x, previous = value]); |
| 50 | + } |
| 51 | + } |
| 52 | + |
| 53 | + return result; |
| 54 | +}; |
0 commit comments