Problem
Find the total area covered by two rectilinear rectangles in a 2D plane.
Each rectangle is defined by its bottom left corner and top right corner as shown in the figure.
Example:
Input: A = -3, B = 0, C = 3, D = 4, E = 0, F = -1, G = 9, H = 2 Output: 45
Note:
Assume that the total area is never beyond the maximum possible value of int.
Solution:
area1 + area2 – overlapped area
Time complexity: O(1)
Space complexity: O(1)
C++
1 2 3 4 5 6 7 8 9 10 11 12 13 |
// Author: Huahua class Solution { public: int computeArea(int A, int B, int C, int D, int E, int F, int G, int H) { int area1 = (C - A) * (D - B); int area2 = (G - E) * (H - F); int x1 = max(A, E); int x2 = max(x1, min(C, G)); int y1 = max(B, F); int y2 = max(y1, min(D, H)); return area1 + area2 - (x2 - x1) * (y2 - y1); } }; |
Java
1 2 3 4 5 6 7 8 9 10 11 12 |
// Author: Huahua class Solution { public int computeArea(int A, int B, int C, int D, int E, int F, int G, int H) { int area1 = (C - A) * (D - B); int area2 = (G - E) * (H - F); int x1 = Math.max(A, E); int x2 = Math.max(x1, Math.min(C, G)); int y1 = Math.max(B, F); int y2 = Math.max(y1, Math.min(D, H)); return area1 + area2 - (x2 - x1) * (y2 - y1); } } |
Python3
1 2 3 4 5 6 7 8 9 10 |
# Author: Huahua class Solution: def computeArea(self, A, B, C, D, E, F, G, H): area1 = (C - A) * (D - B); area2 = (G - E) * (H - F); x1 = max(A, E); x2 = max(x1, min(C, G)); y1 = max(B, F); y2 = max(y1, min(D, H)); return area1 + area2 - (x2 - x1) * (y2 - y1) |