分析
需要略微背诵重叠区域面积的公式,举个例子即可回忆起来(只要记得公式只有一个,不需要分情况讨论即可)。
留意到宽度和高度都至少为0(当两个矩阵不重叠时,可能得出重叠宽度/高度为负数)。换句话说,但凡两个矩阵有重叠,都会遵循面积公式。如果没重叠,会得到负数宽高,则应当限制为0。
如果要证明公式的正确性,需要举几个例子,在面试中比较耗费时间。
答案
class Solution:
def computeArea(self, ax1: int, ay1: int, ax2: int, ay2: int, bx1: int, by1: int, bx2: int, by2: int) -> int:
area1 = (ax2-ax1) * (ay2-ay1)
area2 = (bx2-bx1) * (by2-by1)
overlap_width = min(ax2, bx2) - max(ax1, bx1)
overlap_height = min(ay2, by2) - max(ay1, by1)
overlap_area = max(overlap_width, 0) * max(overlap_height, 0)
return area1 + area2 - overlap_area