3131public class RectangleAreaII850 {
3232 /**
3333 * https://leetcode.com/problems/rectangle-area-ii/
34+ * Sweep Line + Meeting Room + Merge Intervals
3435 */
36+ private static int MOD = 1_000_000_007 ;
3537 public int rectangleArea (int [][] rectangles ) {
3638 int OPEN = 0 , CLOSE = 1 ;
3739 int [][] events = new int [rectangles .length * 2 ][];
@@ -40,42 +42,51 @@ public int rectangleArea(int[][] rectangles) {
4042 events [t ++] = new int []{rec [1 ], OPEN , rec [0 ], rec [2 ]};
4143 events [t ++] = new int []{rec [3 ], CLOSE , rec [0 ], rec [2 ]};
4244 }
43-
4445 Arrays .sort (events , (a , b ) -> Integer .compare (a [0 ], b [0 ]));
4546
4647 List <int []> active = new ArrayList ();
47- int cur_y = events [0 ][0 ];
48+ int currY = events [0 ][0 ];
4849 long ans = 0 ;
4950 for (int [] event : events ) {
5051 int y = event [0 ], typ = event [1 ], x1 = event [2 ], x2 = event [3 ];
51-
52- // Calculate query
53- long query = 0 ;
54- int cur = -1 ;
55- for (int [] xs : active ) {
56- cur = Math .max (cur , xs [0 ]);
57- query += Math .max (xs [1 ] - cur , 0 );
58- cur = Math .max (cur , xs [1 ]);
59- }
60-
61- ans += query * (y - cur_y );
62-
52+ ans += mergeIntervals (active ) * (y - currY );
6353 if (typ == OPEN ) {
6454 active .add (new int []{x1 , x2 });
65- Collections .sort (active , (a , b ) -> Integer .compare (a [0 ], b [0 ]));
6655 } else {
67- for (int i = 0 ; i < active .size (); ++i )
56+ for (int i = 0 ; i < active .size (); ++i ) {
6857 if (active .get (i )[0 ] == x1 && active .get (i )[1 ] == x2 ) {
6958 active .remove (i );
7059 break ;
7160 }
61+ }
7262 }
73-
74- cur_y = y ;
63+ currY = y ;
7564 }
76-
77- ans %= 1_000_000_007 ;
65+ ans %= MOD ;
7866 return (int ) ans ;
7967 }
8068
69+ private long mergeIntervals (List <int []> active ) {
70+ long query = 0 ;
71+ int cur = -1 ;
72+ Collections .sort (active , (a , b ) -> Integer .compare (a [0 ], b [0 ]));
73+ for (int [] xs : active ) {
74+ cur = Math .max (cur , xs [0 ]);
75+ query += Math .max (xs [1 ] - cur , 0 );
76+ cur = Math .max (cur , xs [1 ]);
77+ }
78+ return query ;
79+ }
80+
81+
82+
83+
84+
85+
86+
87+
88+
89+
90+
91+
8192}
0 commit comments