|
| 1 | +// https://leetcode.com/problems/rectangle-area |
| 2 | +// T: O(1) |
| 3 | +// S: O(1) |
| 4 | + |
| 5 | +public class RectangleArea { |
| 6 | + private record Point(int x, int y) {} |
| 7 | + |
| 8 | + private static class Rectangle { |
| 9 | + public final int xl; |
| 10 | + public final int xr; |
| 11 | + public final int yb; |
| 12 | + public final int yt; |
| 13 | + public final int area; |
| 14 | + |
| 15 | + Rectangle(Point lowerLeft, Point upperRight) { |
| 16 | + xl = lowerLeft.x; |
| 17 | + xr = upperRight.x; |
| 18 | + yb = lowerLeft.y; |
| 19 | + yt = upperRight.y; |
| 20 | + area = (upperRight.x - lowerLeft.x) * (upperRight.y - lowerLeft.y); |
| 21 | + } |
| 22 | + |
| 23 | + public static Rectangle from(int x1, int y1, int x2, int y2) { |
| 24 | + final Point a1 = new Point(x1, y1); |
| 25 | + final Point a2 = new Point(x2, y2); |
| 26 | + return new Rectangle(a1, a2); |
| 27 | + } |
| 28 | + |
| 29 | + public Rectangle intersection(Rectangle other) { |
| 30 | + final int intersectionXl = Math.max(xl, other.xl); |
| 31 | + final int intersectionXr = Math.max(intersectionXl, Math.min(xr, other.xr)); |
| 32 | + final int intersectionYb = Math.max(yb, other.yb); |
| 33 | + final int intersectionYt = Math.max(intersectionYb, Math.min(yt, other.yt)); |
| 34 | + |
| 35 | + if (intersectionXl > intersectionXr || intersectionYb > intersectionYt) { |
| 36 | + return null; |
| 37 | + } |
| 38 | + |
| 39 | + return Rectangle.from(intersectionXl, intersectionYb, intersectionXr, intersectionYt); |
| 40 | + } |
| 41 | + } |
| 42 | + |
| 43 | + public static int computeArea(int ax1, int ay1, int ax2, int ay2, int bx1, int by1, int bx2, int by2) { |
| 44 | + final Rectangle rectangle1 = Rectangle.from(ax1, ay1, ax2, ay2); |
| 45 | + final Rectangle rectangle2 = Rectangle.from(bx1, by1, bx2, by2); |
| 46 | + final Rectangle intersection = rectangle1.intersection(rectangle2); |
| 47 | + return rectangle1.area + rectangle2.area - (intersection == null ? 0 : intersection.area); |
| 48 | + } |
| 49 | +} |
0 commit comments