|
| 1 | +/** |
| 2 | +* We are given a list of (axis-aligned) rectangles. Each rectangle[i] = |
| 3 | +* [x1, y1, x2, y2] , where (x1, y1) are the coordinates of the bottom-left |
| 4 | +* corner, and (x2, y2) are the coordinates of the top-right corner of the ith |
| 5 | +* rectangle. |
| 6 | +* |
| 7 | +* Find the total area covered by all rectangles in the plane. Since the |
| 8 | +* answer may be too large, return it modulo 10^9 + 7. |
| 9 | +* |
| 10 | +* https://s3-lc-upload.s3.amazonaws.com/uploads/2018/06/06/rectangle_area_ii_pic.png |
| 11 | +* |
| 12 | +* Example 1: |
| 13 | +* Input: [[0,0,2,2],[1,0,2,3],[1,0,3,1]] |
| 14 | +* Output: 6 |
| 15 | +* Explanation: As illustrated in the picture. |
| 16 | +* |
| 17 | +* Example 2: |
| 18 | +* Input: [[0,0,1000000000,1000000000]] |
| 19 | +* Output: 49 |
| 20 | +* Explanation: The answer is 10^18 modulo (10^9 + 7), which is (10^9)^2 = (-7)^2 = 49. |
| 21 | +* |
| 22 | +* Note: |
| 23 | +* 1 <= rectangles.length <= 200 |
| 24 | +* rectanges[i].length = 4 |
| 25 | +* 0 <= rectangles[i][j] <= 10^9 |
| 26 | +* The total area covered by all rectangles will never exceed 2^63 - 1 and |
| 27 | +* thus will fit in a 64-bit signed integer. |
| 28 | +*/ |
| 29 | + |
| 30 | + |
| 31 | +public class RectangleAreaII850 { |
| 32 | +/** |
| 33 | +* https://leetcode.com/problems/rectangle-area-ii/ |
| 34 | +*/ |
| 35 | +public int rectangleArea(int[][] rectangles) { |
| 36 | +int OPEN = 0, CLOSE = 1; |
| 37 | +int[][] events = new int[rectangles.length * 2][]; |
| 38 | +int t = 0; |
| 39 | +for (int[] rec: rectangles) { |
| 40 | +events[t++] = new int[]{rec[1], OPEN, rec[0], rec[2]}; |
| 41 | +events[t++] = new int[]{rec[3], CLOSE, rec[0], rec[2]}; |
| 42 | +} |
| 43 | + |
| 44 | +Arrays.sort(events, (a, b) -> Integer.compare(a[0], b[0])); |
| 45 | + |
| 46 | +List<int[]> active = new ArrayList(); |
| 47 | +int cur_y = events[0][0]; |
| 48 | +long ans = 0; |
| 49 | +for (int[] event: events) { |
| 50 | +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 | + |
| 63 | +if (typ == OPEN) { |
| 64 | +active.add(new int[]{x1, x2}); |
| 65 | +Collections.sort(active, (a, b) -> Integer.compare(a[0], b[0])); |
| 66 | +} else { |
| 67 | +for (int i = 0; i < active.size(); ++i) |
| 68 | +if (active.get(i)[0] == x1 && active.get(i)[1] == x2) { |
| 69 | +active.remove(i); |
| 70 | +break; |
| 71 | +} |
| 72 | +} |
| 73 | + |
| 74 | +cur_y = y; |
| 75 | +} |
| 76 | + |
| 77 | +ans %= 1_000_000_007; |
| 78 | +return (int) ans; |
| 79 | +} |
| 80 | + |
| 81 | +} |
0 commit comments