|
| 1 | +/** |
| 2 | + * 391. Perfect Rectangle |
| 3 | + * https://leetcode.com/problems/perfect-rectangle/ |
| 4 | + * Difficulty: Hard |
| 5 | + * |
| 6 | + * Given an array rectangles where rectangles[i] = [xi, yi, ai, bi] represents an axis-aligned |
| 7 | + * rectangle. The bottom-left point of the rectangle is (xi, yi) and the top-right point of it |
| 8 | + * is (ai, bi). |
| 9 | + * |
| 10 | + * Return true if all the rectangles together form an exact cover of a rectangular region. |
| 11 | + */ |
| 12 | + |
| 13 | +/** |
| 14 | + * @param {number[][]} rectangles |
| 15 | + * @return {boolean} |
| 16 | + */ |
| 17 | +var isRectangleCover = function(rectangles) { |
| 18 | + const result = new Set(); |
| 19 | + let area = 0; |
| 20 | + let minX = Infinity; |
| 21 | + let maxX = -Infinity; |
| 22 | + let minY = Infinity; |
| 23 | + let maxY = -Infinity; |
| 24 | + |
| 25 | + for (const [x1, y1, x2, y2] of rectangles) { |
| 26 | + area += (x2 - x1) * (y2 - y1); |
| 27 | + minX = Math.min(minX, x1); |
| 28 | + minY = Math.min(minY, y1); |
| 29 | + maxX = Math.max(maxX, x2); |
| 30 | + maxY = Math.max(maxY, y2); |
| 31 | + for (const corner of [`${x1},${y1}`, `${x2},${y1}`, `${x1},${y2}`, `${x2},${y2}`]) { |
| 32 | + result.has(corner) ? result.delete(corner) : result.add(corner); |
| 33 | + } |
| 34 | + } |
| 35 | + |
| 36 | + return area === (maxX - minX) * (maxY - minY) && result.size === 4 |
| 37 | + && result.has(`${minX},${minY}`) && result.has(`${maxX},${minY}`) |
| 38 | + && result.has(`${minX},${maxY}`) && result.has(`${maxX},${maxY}`); |
| 39 | +}; |
0 commit comments