1
+ class PerfectRectangle391 {
2
+ public boolean isRectangleCover (int [][] rectangles ) {
3
+ if (rectangles ==null || rectangles .length ==0 || rectangles [0 ].length ==0 )
4
+ return false ;
5
+ int N = rectangles .length ;
6
+
7
+ // Identify Overlaps - TreeSet with custom comparator: O(n*log(n))
8
+ // Sum of areas equal to covering area : O(n)
9
+ // Overall solution : O(n*log(n))
10
+
11
+ Set <int []> set = new TreeSet <>((int [] a , int [] b ) -> {
12
+ if (a [3 ] <= b [1 ]) {
13
+ return -1 ;
14
+ } else if (a [1 ] >= b [3 ]) {
15
+ return 1 ;
16
+ } else if (a [2 ] <= b [0 ]) {
17
+ return -1 ;
18
+ } else if (a [0 ] >= b [2 ]) {
19
+ return 1 ;
20
+ } else return 0 ;
21
+ });
22
+
23
+ int [] coverBottomLeft = {rectangles [0 ][0 ], rectangles [0 ][1 ]};
24
+ int [] coverTopRight = {rectangles [0 ][2 ], rectangles [0 ][3 ]};
25
+
26
+ long totalArea = 0 ;
27
+ for (int i =0 ; i <N ; i ++) {
28
+ if (!set .add (rectangles [i ]))
29
+ return false ;
30
+
31
+ totalArea += ((long )(rectangles [i ][3 ] - rectangles [i ][1 ])) * ((long )(rectangles [i ][2 ] - rectangles [i ][0 ]));
32
+ coverBottomLeft [0 ] = Math .min (coverBottomLeft [0 ], rectangles [i ][0 ]);
33
+ coverBottomLeft [1 ] = Math .min (coverBottomLeft [1 ], rectangles [i ][1 ]);
34
+ coverTopRight [0 ] = Math .max (coverTopRight [0 ], rectangles [i ][2 ]);
35
+ coverTopRight [1 ] = Math .max (coverTopRight [1 ], rectangles [i ][3 ]);
36
+ }
37
+ long coverArea = ((long )(coverTopRight [0 ] - coverBottomLeft [0 ])) * ((long )(coverTopRight [1 ] - coverBottomLeft [1 ]));
38
+
39
+ return (totalArea == coverArea );
40
+ }
41
+ }
0 commit comments