1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37
| class Solution {
private static final int MOD = (int) 1e9 + 7;
public int rectangleArea(int[][] rectangles) { List<Integer> list = new ArrayList<>(); for (int[] rectangle : rectangles) { list.add(rectangle[0]); list.add(rectangle[2]); } Collections.sort(list); long ans = 0; for (int i = 1; i < list.size(); ++i) { int a = list.get(i - 1), b = list.get(i), len = b - a; if (len == 0) continue; List<int[]> lines = new ArrayList<>(); for (int[] rectangle : rectangles) { if (rectangle[0] <= a && b <= rectangle[2]) lines.add(new int[]{rectangle[1], rectangle[3]}); } lines.sort((a, b) -> a[0] != b[0] ? a[0] - b[0] : a[1] - b[1]); long total = 0, l = -1, r = -1; for (int[] cur : lines) { if (cur[0] > r) { total += r - l; l = cur[0]; r = cur[1]; } else if (cur[1] > r) { r = cur[1]; } } total += r - l; ans += total * len; ans %= MOD; } return (int) ans; } }
|