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.
Rectangle Area
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.
解题要点:
相交部分分成左右,上下四个点处理,如以下。
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
"""
a1 = (C - A) * (D - B)
a2 = (G - E) * (H - F)
left = max(A, E)
right = max(left, min(C, G))
down = max(B, F)
top = max(down, min(D, H))
return a1 + a2 - (right - left) * (top - down)