- 223.矩形面积
- 题目描述
- 思路:计算重叠面积
223.矩形面积 题目描述
矩形面积
思路:计算重叠面积
两个矩形覆盖的总面积等于两个矩形的面积之和减去两个矩形的重叠部分的面积。由于两个矩形的左下顶点和右上顶点已知,所以两个矩形的面积可以直接计算。如果两个矩形重叠,则两个矩形重叠部分也是矩形,重叠部分的面积,可以根据重叠部分的边界计算。
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) overlapWidth = min(ax2, bx2) - max(ax1, bx1) overlapHeight = min(ay2, by2) - max(ay1, by1) overlap = max(overlapWidth, 0) * max(overlapHeight, 0) return area1 + area2 - overlap