?LeetCode刷題實(shí)戰(zhàn)391:完美矩形
Given an array rectangles where rectangles[i] = [xi, yi, ai, bi] represents an axis-aligned rectangle. The bottom-left point of the rectangle is (xi, yi) and the top-right point of it is (ai, bi).
Return true if all the rectangles together form an exact cover of a rectangular region.

示例
示例 1:
rectangles = [
[1,1,3,3],
[3,1,4,2],
[3,2,4,4],
[1,3,2,4],
[2,3,3,4]
]
返回 true。5個(gè)矩形一起可以精確地覆蓋一個(gè)矩形區(qū)域。
示例 2:
rectangles = [
[1,1,2,3],
[1,3,2,4],
[3,1,4,2],
[3,2,4,4]
]
返回 false。兩個(gè)矩形之間有間隔,無法覆蓋成一個(gè)矩形。
示例 3:
rectangles = [
[1,1,3,3],
[3,1,4,2],
[1,3,2,4],
[3,2,4,4]
]
返回 false。圖形頂端留有間隔,無法覆蓋成一個(gè)矩形。
示例 4:
rectangles = [
[1,1,3,3],
[3,1,4,2],
[1,3,2,4],
[2,2,4,4]
]
返回 false。因?yàn)橹虚g有相交區(qū)域,雖然形成了矩形,但不是精確覆蓋。
解題



class Solution {
public boolean isRectangleCover(int[][] rectangles) {
// 完美矩形的左下角和右上角坐標(biāo)
int X1 = Integer.MAX_VALUE, Y1 = Integer.MAX_VALUE;
int X2 = Integer.MIN_VALUE, Y2 = Integer.MIN_VALUE;
// 小矩形面積之和
int areas = 0;
// 記錄所有頂點(diǎn)的出現(xiàn)情況
Set<String> points = new HashSet<>();
for (int[] rectangle : rectangles) {
int x1 = rectangle[0], y1 = rectangle[1], x2 = rectangle[2], y2 = rectangle[3];
// 更新坐標(biāo)
X1 = Math.min(x1, X1);
Y1 = Math.min(y1, Y1);
X2 = Math.max(x2, X2);
Y2 = Math.max(y2, Y2);
areas += (x2 - x1) * (y2 - y1);
// 判斷頂點(diǎn)是否出現(xiàn)過
String[] ps = {x1 + " " + y1, x2 + " " + y2, x1 + " " + y2, x2 + " " + y1};
for (String s : ps) {
// 沒有出現(xiàn)過,添加;否則,移除
if(points.contains(s)){
points.remove(s);
} else {
points.add(s);
}
}
}
// 面積是否相等
int expected = (X2 - X1) * (Y2 -Y1);
if(areas != expected){
return false;
}
// 頂點(diǎn)情況是否滿足
if(points.size() != 4 || !points.contains(X1 + " " + Y1) || !points.contains(X2 + " " + Y2) || !points.contains(X1 + " " + Y2) || !points.contains(X2 + " " + Y1)){
return false;
}
return true;
}
}
LeetCode1-380題匯總,希望對(duì)你有點(diǎn)幫助!
LeetCode刷題實(shí)戰(zhàn)381:O(1) 時(shí)間插入、刪除和獲取隨機(jī)元素
LeetCode刷題實(shí)戰(zhàn)382:鏈表隨機(jī)節(jié)點(diǎn)
LeetCode刷題實(shí)戰(zhàn)383:贖金信
LeetCode刷題實(shí)戰(zhàn)384:打亂數(shù)組
LeetCode刷題實(shí)戰(zhàn)385:迷你語法分析器
