[LeetCode]60. 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](https://leetcode.com/static/images/problemset/rectangle_area.png)
Assume that the total area is never beyond the maximum possible value of int.
Credits:
Special thanks to @mithmatt for adding this problem, creating the above image and all test cases.
Subscribe to see which companies asked this question
解法:注意前提条件:矩形的边和坐标轴是平行的。所有的不相交的情况只有四种:一个矩形在另一个的上下左右四个位置不重叠,这四种情况下返回两个矩形面积之和。其他所有情况下两个矩形是有交集的。由于交集都是在中间,所以横边的左端点是两个矩形左顶点横坐标的较大值,右端点是两个矩形右顶点的较小值,同理,竖边的下端点是两个矩形下顶点纵坐标的较大值,上端点是两个矩形上顶点纵坐标的较小值。
class Solution { public: int computeArea(int A, int B, int C, int D, int E, int F, int G, int H) { int res = (C - A) * (D - B) + (G - E) * (H - F); if (!(A >= G || B >= H || E >= C || F >= D)) res -= (min(G, C) - max(E, A)) * (min(H, D) - max(F, B)); return res; } };