本文最后更新于237 天前,其中的信息可能已经过时,如有错误请发送邮件到2446865563@qq.com
1.题目基本信息
1.1.题目描述
给你 二维 平面上两个 由直线构成且边与坐标轴平行/垂直 的矩形,请你计算并返回两个矩形覆盖的总面积。
每个矩形由其 左下 顶点和 右上 顶点坐标表示:
-
第一个矩形由其左下顶点 (ax1, ay1) 和右上顶点 (ax2, ay2) 定义。
-
第二个矩形由其左下顶点 (bx1, by1) 和右上顶点 (bx2, by2) 定义。
1.2.题目地址
https://leetcode.cn/problems/rectangle-area/description/
2.解题方法
2.1.解题思路
根据投影计算相交区域的面积。线段[ax1,ax2]和线段[bx1,bx2]的交集,线段[ay1,ay2]与线段[by1,by2]的交集
3.解题代码
python代码
class Solution:
def computeArea(self, ax1: int, ay1: int, ax2: int, ay2: int, bx1: int, by1: int, bx2: int, by2: int) -> int:
# 思路:投影计算相交区域的面积。线段[ax1,ax2]和线段[bx1,bx2]的交集,线段[ay1,ay2]与线段[by1,by2]的交集
width = min(ax2, bx2) - max(ax1, bx1)
height = min(ay2, by2) - max(ay1, by1)
area1 = abs((ax2 - ax1) * (ay2 - ay1))
area2 = abs((bx2 - bx1) * (by2 - by1))
area3 = max(width, 0) * max(height, 0)
return area1 + area2 - area3
4.执行结果










