223. Rectangle Area [easy] (Python)

这篇博客介绍了LeetCode上的第223题,题目要求计算两个矩形在2D平面上的覆盖总面积。内容包括题目链接、原题翻译、解题思路以及两种不同的解决方案。思路一先判断矩形是否重叠再计算面积,思路二则直接计算重叠部分的面积。博主分享了相关代码,并欢迎读者指正。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目链接

https://leetcode.com/problems/rectangle-area/

题目原文

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

Assume that the total area is never beyond the maximum possible value of int.

题目翻译

求两个2维矩形覆盖的总面积。每个矩形由左下角坐标和右上角坐标定义,覆盖情况见示意图(图示在上面)。假定覆盖总面积不超过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
        """
        if B>=H or E>=C or F>=D or A>=G:
            return (C-A) * (D-B) + (G-E) * (H-F)
        width = min(C,G) - max(A,E)
        height = min(D,H) - max(B,F)
        return (C-A) * (D-B) + (G-E) * (H-F) - width * height

思路二

直接计算重叠部分面积,当不交叠时长度或宽度为零。

代码一

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
        """
        width = max(0, min(C,G) - max(A,E))
        height = max(0, min(D,H) - max(B,F))
        return (C-A) * (D-B) + (G-E) * (H-F) - width * height

说明
同样的思路,不过将交叠的矩形的左下、右上坐标求出来,可能会更好理解一些。

代码二

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
        """
        left = max(A,E)
        right = max(min(C,G), left)
        bottom = max(B,F)
        top = max(min(D,H), bottom)
        return (C-A) * (D-B) + (G-E) * (H-F) - (right-left) * (top-bottom)

PS: 新手刷LeetCode,新手写博客,写错了或者写的不清楚还请帮忙指出,谢谢!
转载请注明:http://blog.youkuaiyun.com/coder_orz/article/details/51679907

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值