|
| 1 | +/** |
| 2 | + * 3531. Count Covered Buildings |
| 3 | + * https://leetcode.com/problems/count-covered-buildings/ |
| 4 | + * Difficulty: Medium |
| 5 | + * |
| 6 | + * You are given a positive integer n, representing an n x n city. You are also given |
| 7 | + * a 2D grid buildings, where buildings[i] = [x, y] denotes a unique building located |
| 8 | + * at coordinates [x, y]. |
| 9 | + * |
| 10 | + * A building is covered if there is at least one building in all four directions: |
| 11 | + * left, right, above, and below. |
| 12 | + * |
| 13 | + * Return the number of covered buildings. |
| 14 | + */ |
| 15 | + |
| 16 | +/** |
| 17 | + * @param {number} n |
| 18 | + * @param {number[][]} buildings |
| 19 | + * @return {number} |
| 20 | + */ |
| 21 | +var countCoveredBuildings = function(n, buildings) { |
| 22 | + const rowBuildings = new Map(); |
| 23 | + const colBuildings = new Map(); |
| 24 | + let result = 0; |
| 25 | + |
| 26 | + for (const [x, y] of buildings) { |
| 27 | + if (!rowBuildings.has(x)) rowBuildings.set(x, []); |
| 28 | + if (!colBuildings.has(y)) colBuildings.set(y, []); |
| 29 | + rowBuildings.get(x).push(y); |
| 30 | + colBuildings.get(y).push(x); |
| 31 | + } |
| 32 | + for (const coords of rowBuildings.values()) { |
| 33 | + coords.sort((a, b) => a - b); |
| 34 | + } |
| 35 | + for (const coords of colBuildings.values()) { |
| 36 | + coords.sort((a, b) => a - b); |
| 37 | + } |
| 38 | + for (const [x, y] of buildings) { |
| 39 | + const rowCoords = rowBuildings.get(x); |
| 40 | + const colCoords = colBuildings.get(y); |
| 41 | + const hasLeft = rowCoords[0] < y; |
| 42 | + const hasRight = rowCoords[rowCoords.length - 1] > y; |
| 43 | + const hasAbove = colCoords[0] < x; |
| 44 | + const hasBelow = colCoords[colCoords.length - 1] > x; |
| 45 | + |
| 46 | + if (hasLeft && hasRight && hasAbove && hasBelow) { |
| 47 | + result++; |
| 48 | + } |
| 49 | + } |
| 50 | + |
| 51 | + return result; |
| 52 | +}; |
0 commit comments