223 Rectangle Area
链接: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.
Credits:
Special thanks to @mithmatt for adding this problem, creating the above image and all test cases.
Hide Tags Math
这个问题是求两个矩形覆盖区域的面积,需要注意的是当两个矩形有重合区域的时候,那么需要减去重合的区域。所以问题的关键就是求重合区域的大小。
定义:
a= max(A, E);
b= max(B, F);
c= min(C, G);
d= min(D, H);
那么可以知道重合区域的左直线x左边是a,右直线的x坐标是c,上面横向的y坐标是d,下面横线的y坐标是b。那么当c<=或者d<=b的时候没有重叠。反之则有重叠,面积计算方式是 (d-b) * (c -a)。
class Solution {
public:
int computeArea(int A, int B, int C, int D, int E, int F, int G, int H) {
int result = (D - B) * (C - A) + (H - F) * (G - E);
int a,b,c,d;
a= max(A, E);
b= max(B, F);
c= min(C, G);
d= min(D, H);
if (d <= b || c<= a) return result;
return result - (d-b) * (c -a);
}
};