Find the total area covered by two rectilinearrectangles in a 2D plane.html
Each rectangle is defined by its bottom left corner and top right corner as shown in the figure.git
Example:github
Input: A = -3, B = 0, C = 3, D = 4, E = 0, F = -1, G = 9, H = 2 Output: 45
Note:post
Assume that the total area is never beyond the maximum possible value of int.this
Credits:
Special thanks to @mithmatt for adding this problem, creating the above image and all test cases.url
这道题不算一道很难的题,但博主仍是花了好久才作出来,刚开始尝试找出因此有重叠的状况,发现有不少种状况,很麻烦。后来换了一种思路,尝试先找出全部的不相交的状况,只有四种,一个矩形在另外一个的上下左右四个位置不重叠,这四种状况下返回两个矩形面积之和。其余全部状况下两个矩形是有交集的,这时候只要算出长和宽,便可求出交集区域的大小,而后从两个矩型面积之和中减去交集面积就是最终答案。求交集区域的长和宽也不难,因为交集都是在中间,因此横边的左端点是两个矩形左顶点横坐标的较大值,右端点是两个矩形右顶点的较小值,同理,竖边的下端点是两个矩形下顶点纵坐标的较大值,上端点是两个矩形上顶点纵坐标的较小值。以前是能够直接将 sum1 和 sum2 加起来的,能够后来OJ搞了些恶心的 test case,使得直接把 sum1 和 sum2 相加会溢出,因此只好分开了,若两个矩形有重叠,那么返回的时候也不能让 sum1 和 sum2 直接相加,中间必定要先减去重叠部分才行,代码以下:spa
解法一:code
class Solution { public: int computeArea(int A, int B, int C, int D, int E, int F, int G, int H) { int sum1 = (C - A) * (D - B), sum2 = (H - F) * (G - E); if (E >= C || F >= D || B >= H || A >= G) return sum1 + sum2; return sum1 - ((min(G, C) - max(A, E)) * (min(D, H) - max(B, F))) + sum2; } };
本来上面解法的三行还能够丧心病狂地合成一行,可是因为 OJ 使坏,加了些变态的 test case,使得咱们仍是得拆分开来,先求出重叠区间的四个点 left,bottom,right,top 的值,而后再求出重叠区间的面积,避免溢出,参见代码以下:htm
解法二:blog
class Solution { public: int computeArea(int A, int B, int C, int D, int E, int F, int G, int H) { int left = max(A,E), right = max(min(C,G), left); int bottom = max(B,F), top = max(min(D,H), bottom); return (C - A) * (D - B) - (right - left) * (top - bottom) + (G - E) * (H - F); } };
Github 同步地址:
https://github.com/grandyang/leetcode/issues/223
相似题目:
参考资料:
https://leetcode.com/problems/rectangle-area/
https://leetcode.com/problems/rectangle-area/discuss/62149/Just-another-short-way