LeetCode刷题实战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个矩形一起可以精确地覆盖一个矩形区域。
示例 2:
rectangles = [
[1,1,2,3],
[1,3,2,4],
[3,1,4,2],
[3,2,4,4]
]
返回 false。两个矩形之间有间隔,无法覆盖成一个矩形。
示例 3:
rectangles = [
[1,1,3,3],
[3,1,4,2],
[1,3,2,4],
[3,2,4,4]
]
返回 false。图形顶端留有间隔,无法覆盖成一个矩形。
示例 4:
rectangles = [
[1,1,3,3],
[3,1,4,2],
[1,3,2,4],
[2,2,4,4]
]
返回 false。因为中间有相交区域,虽然形成了矩形,但不是精确覆盖。
解题
class Solution {
public boolean isRectangleCover(int[][] rectangles) {
// 完美矩形的左下角和右上角坐标
int X1 = Integer.MAX_VALUE, Y1 = Integer.MAX_VALUE;
int X2 = Integer.MIN_VALUE, Y2 = Integer.MIN_VALUE;
// 小矩形面积之和
int areas = 0;
// 记录所有顶点的出现情况
Set<String> points = new HashSet<>();
for (int[] rectangle : rectangles) {
int x1 = rectangle[0], y1 = rectangle[1], x2 = rectangle[2], y2 = rectangle[3];
// 更新坐标
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);
// 判断顶点是否出现过
String[] ps = {x1 + " " + y1, x2 + " " + y2, x1 + " " + y2, x2 + " " + y1};
for (String s : ps) {
// 没有出现过,添加;否则,移除
if(points.contains(s)){
points.remove(s);
} else {
points.add(s);
}
}
}
// 面积是否相等
int expected = (X2 - X1) * (Y2 -Y1);
if(areas != expected){
return false;
}
// 顶点情况是否满足
if(points.size() != 4 || !points.contains(X1 + " " + Y1) || !points.contains(X2 + " " + Y2) || !points.contains(X1 + " " + Y2) || !points.contains(X2 + " " + Y1)){
return false;
}
return true;
}
}
LeetCode刷题实战381:O(1) 时间插入、删除和获取随机元素
评论