题目链接
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.
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

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

被折叠的 条评论
为什么被折叠?



