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
| class Solution { public int computeArea(int ax1, int ay1, int ax2, int ay2, int bx1, int by1, int bx2, int by2) { int first = computeRectangle(ax1, ay1, ax2, ay2); int second = computeRectangle(bx1, by1, bx2, by2); return first + second - calcIntersectArea(ax1, ay1, ax2, ay2, bx1, by1, bx2, by2); }
private int computeRectangle(int x1, int y1, int x2, int y2) { return (x2 - x1) * (y2 - y1); } private int calcIntersectArea(int ax1, int ay1, int ax2, int ay2, int bx1, int by1, int bx2, int by2) { if (bx2 <= ax1 || ax2 <= bx1 || ay2 <= by1 || by2 <= ay1) { return 0; } int x = calcLine(ax1, ax2, bx1, bx2); int y = calcLine(ay1, ay2, by1, by2); return x * y; } private int calcLine(int a1, int a2, int b1, int b2) { return Math.min(b2, a2) - Math.max(b1, a1); } }
|