|
| 1 | +package com..houbb.leetcode.datastruct.sweepline; |
| 2 | + |
| 3 | +import java.util.ArrayList; |
| 4 | +import java.util.Arrays; |
| 5 | +import java.util.Collections; |
| 6 | +import java.util.List; |
| 7 | + |
| 8 | +public class T223_rectangleArea_V2_Sweepline { |
| 9 | + |
| 10 | + |
| 11 | +public static void main(String[] args) { |
| 12 | +computeArea(1,2,3,4,5,6,7,8); |
| 13 | + |
| 14 | +} |
| 15 | + |
| 16 | +public static int computeArea(int ax1, int ay1, int ax2, int ay2, int bx1, int by1, int bx2, int by2) { |
| 17 | +int[][] arr = new int[2][]; |
| 18 | +arr[0] = new int[]{ax1, ay1, ax2, ay2}; |
| 19 | +arr[1] = new int[]{bx1, by1, bx2, by2}; |
| 20 | +Arrays.sort(arr, (o1, o2) -> o1[1] == o2[1] ? o1[3] - o2[3] : o1[1] - o2[1]); |
| 21 | +List<Integer> xList = Arrays.asList(ax1, ax2, bx1, bx2); |
| 22 | +Collections.sort(xList); |
| 23 | +int ans = 0; |
| 24 | +for (int i = 1; i < 4; i++) { |
| 25 | +int width = xList.get(i) - xList.get(i-1); |
| 26 | +for (int[] ints : getLine(xList.get(i-1), xList.get(i), arr)) { |
| 27 | +ans += width * (ints[1] - ints[0]); |
| 28 | +} |
| 29 | +} |
| 30 | +return ans; |
| 31 | +} |
| 32 | + |
| 33 | +private static List<int[]> getLine(int x1, int x2, int[][] arr) { |
| 34 | +List<int[]> list = new ArrayList<>(); |
| 35 | +for (int[] ints : arr) { |
| 36 | +if (x1 >= ints[0] && x2 <= ints[2]) { |
| 37 | +if (list.isEmpty()) { |
| 38 | +list.add(new int[]{ints[1], ints[3]}); |
| 39 | +} else { |
| 40 | +int[] tmp = list.get(list.size() - 1); |
| 41 | +if (tmp[1] < ints[1]) { |
| 42 | +list.add(new int[]{ints[1], ints[3]}); |
| 43 | +} else if (tmp[1] < ints[3]) { |
| 44 | +tmp[1] = ints[3]; |
| 45 | +} |
| 46 | +} |
| 47 | +} |
| 48 | +} |
| 49 | +return list; |
| 50 | +} |
| 51 | + |
| 52 | +} |
0 commit comments