Description:
Given N axis-aligned rectangles where N > 0, determine if they all together form an exact cover of a rectangular region.
Each rectangle is represented as a bottom-left point and a top-right point. For example, a unit square is represented as [1,1,2,2]. (coordinate of bottom-left point is (1, 1) and top-right point is (2, 2)).
问题描述:
给定N个矩形,判断它们是否正好(注意是正好,存在相交的多于区域也不行)形成一个矩形区域
每一个矩形由左下角和右上角的点的坐标进行表示,例如一个单位正方形表示为[1, 1, 2, 2](左下角的点的坐标为(1, 1), 右上角的点的坐标为(2, 2))
问题分析:
N个矩形正好构成一个矩形区域需要满足2个条件
所有小矩形的面积加起来等于大矩形的面积(显而易见)
四个顶点唯一,其他的点成对出现
我们只需要检查是否满足这两个性质就可以了
解法:
class Solution {
public boolean isRectangleCover(int[][] rectangles) {
//(x1, y1)为左下角顶点,(x2, y2)为右上角顶点
int x1 = Integer.MAX_VALUE, y1 = Integer.MAX_VALUE, x2 = Integer.MIN_VALUE, y2 = Integer.MIN_VALUE;
//sum为所有的矩形的面积之和
int sum = 0;
//保存见过的点
Set<String> set = new HashSet();
for(int[] rec : rectangles){
x1 = Math.min(x1, rec[0]);
y1 = Math.min(y1, rec[1]);
x2 = Math.max(x2, rec[2]);
y2 = Math.max(y2, rec[3]);
sum += (rec[2] - rec[0]) * (rec[3] - rec[1]);
String s1 = rec[0] + "" + rec[1];
String s2 = rec[0] + "" + rec[3];
String s3 = rec[2] + "" + rec[3];
String s4 = rec[2] + "" + rec[1];
//若见过该点,则一定不是顶点,删除
if(!set.add(s1)) set.remove(s1);
if(!set.add(s2)) set.remove(s2);
if(!set.add(s3)) set.remove(s3);
if(!set.add(s4)) set.remove(s4);
}
//判断顶点是否只有一个并且set中是否只有4个顶点(因为其他点为2个,都被删除了)
if(!set.contains(x1 + "" + y1) || !set.contains(x1 + "" + y2) || !set.contains(x2 + "" + y2) || !set.contains(x2 + "" + y1) || !(set.size() == 4)) return false;
//判断所有矩形面积之和是否等于矩形区域的面积
return sum == (x2 - x1) * (y2- y1);
}
}