問題:orm
Given N axis-aligned rectangles where N > 0, determine if they all together form an exact cover of a rectangular region.rem
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)).get
Example 1:it
rectangles = [ [1,1,3,3], [3,1,4,2], [3,2,4,4], [1,3,2,4], [2,3,3,4] ] Return true. All 5 rectangles together form an exact cover of a rectangular region.
Example 2:io
rectangles = [ [1,1,2,3], [1,3,2,4], [3,1,4,2], [3,2,4,4] ] Return false. Because there is a gap between the two rectangular regions.
Example 3:form
rectangles = [ [1,1,3,3], [3,1,4,2], [1,3,2,4], [3,2,4,4] ] Return false. Because there is a gap in the top center.
Example 4:class
rectangles = [ [1,1,3,3], [3,1,4,2], [1,3,2,4], [2,2,4,4] ] Return false. Because two of the rectangles overlap with each other.
解決:angular
【題意】這道題是說給了一堆小矩形的座標(左下角和右上角圍成的),問其可否組合成一個完美的矩形(剛恰好,很少,很多,不交叉重複)。im
① 核心思想:可以正好圍成一個矩形的狀況就是:top
有且只有:
- 最左下 最左上 最右下 最右上 的四個點只出現過一次,其餘確定是成對出現的(保證徹底覆蓋)
- 上面四個點圍成的面積,正好等於全部子矩形的面積之和(保證不重複)
public class Solution { //106ms
public boolean isRectangleCover(int[][] rectangles) {
int x1 = Integer.MAX_VALUE;
int x2 = Integer.MIN_VALUE;
int y1 = Integer.MAX_VALUE;
int y2 = Integer.MIN_VALUE;
int area = 0;
Set<String> set = new HashSet();
for(int[] rect : rectangles) {
area += (rect[2] - rect[0]) * (rect[3] - rect[1]);
x1 = Math.min(x1, rect[0]);
y1 = Math.min(y1, rect[1]);
x2 = Math.max(x2, rect[2]);
y2 = Math.max(y2, rect[3]);
String s1 = rect[0] + " " + rect[1];
String s2 = rect[0] + " " + rect[3];
String s3 = rect[2] + " " + rect[1];
String s4 = rect[2] + " " + rect[3];
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);
}
// condition 1
if(area != (x2 - x1) * (y2 - y1)) return false;
// condition 2
return set.contains(x1 + " " + y1) && set.contains(x1 + " " + y2) && set.contains(x2 + " " + y1) && set.contains(x2 + " " + y2) && set.size() == 4;
} }