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.
解题方法
主要就是考查是否能够考虑到各种情况,在做这种题目的时候最好画出各种图来处理
- 不重叠的情况,在左右
- 重叠的面积的计算,两个长方形的面积 - 重叠部分的面积
在discuss里看到了一个很巧妙的做法, assume两个bottom-left的点都在right-up点的左下,这样才可能重叠。 直接求出如果重叠的话那么边界的坐标,如果边界左边不能组成一个rectangle的时候,说明并不重叠。
Solution
leftX = max(A, E)
leftY = max(B, F)
rightX = min(C, G)
rightY = min(D, H)
totalArea = (C-A) * (D-B) + (G-E) * (H-F)
if rightX < leftX or rightY < leftY:
# means they are not overlapped
return totalArea
else:
overlapArea = (rightX - leftX) * (rightY - leftY)
return totalArea - overlapArea