Question
Formatted question description: https://leetcode.ca/all/223.html
223. Rectangle Area
Level
Medium
Description
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.
Algorithm
First find out all the cases of disjoint
, there are only four types, one rectangle does not overlap at the top, bottom, left, and right positions of the other. In these four cases, the sum of the area of the two rectangles is returned.
In all other cases, two rectangles have an intersection. At this time, just calculate the length and width to find the size of the intersection area, and then subtract the intersection area from the sum of the two rectangular areas, to get the final answer.
Code
Java

public class Rectangle_Area { class Solution { public int computeArea(int A, int B, int C, int D, int E, int F, int G, int H) { int erea1 = (C  A) * (D  B), area2 = (H  F) * (G  E); if (E >= C  F >= D  B >= H  A >= G) { return erea1 + area2; } else { return erea1 + area2  ((Math.min(G, C)  Math.max(A, E)) * (Math.min(D, H)  Math.max(B, F))); } } } }

Todo

class Solution(object): def computeArea(self, A, B, C, D, E, F, G, H): """ :type A: int :type B: int :type C: int :type D: int :type E: int :type F: int :type G: int :type H: int :rtype: int """ area = (C  A) * (D  B) + (G  E) * (H  F) overlap = max(min(C, G)  max(A, E), 0) * max(min(D, H)  max(B, F), 0) return area  overlap