Skip to content

Commit c8bbaca

Browse files
committed
Add solution #391
1 parent 3ce8dd2 commit c8bbaca

File tree

2 files changed

+40
-0
lines changed

2 files changed

+40
-0
lines changed

README.md

+1
Original file line numberDiff line numberDiff line change
@@ -309,6 +309,7 @@
309309
388|[Longest Absolute File Path](./0388-longest-absolute-file-path.js)|Medium|
310310
389|[Find the Difference](./0389-find-the-difference.js)|Easy|
311311
390|[Elimination Game](./0390-elimination-game.js)|Medium|
312+
391|[Perfect Rectangle](./0391-perfect-rectangle.js)|Hard|
312313
392|[Is Subsequence](./0392-is-subsequence.js)|Easy|
313314
394|[Decode String](./0394-decode-string.js)|Medium|
314315
395|[Longest Substring with At Least K Repeating Characters](./0395-longest-substring-with-at-least-k-repeating-characters.js)|Medium|

solutions/0391-perfect-rectangle.js

+39
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
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

Comments
 (0)