<p style="box-sizing: border-box; margin-top: 0px; margin-bottom: 10px; color: rgb(51, 51, 51); font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif; font-size: 14px; line-height: 30px;">Find the total area covered by two <span style="box-sizing: border-box; font-weight: 700;">rectilinear</span> rectangles in a <span style="box-sizing: border-box; font-weight: 700;">2D</span> plane.</p><p style="box-sizing: border-box; margin-top: 0px; margin-bottom: 10px; color: rgb(51, 51, 51); font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif; font-size: 14px; line-height: 30px;">Each rectangle is defined by its bottom left corner and top right corner as shown in the figure.</p><div style="box-sizing: border-box; color: rgb(51, 51, 51); font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif; font-size: 14px; line-height: 30px; width: 529px; height: 300px; background-color: rgb(235, 235, 235);"><img src="https://leetcode.com/static/images/problemset/rectangle_area.png" border="0" alt="Rectangle Area" style="box-sizing: border-box; border: 0px; vertical-align: middle;" /></div><div style="box-sizing: border-box; color: rgb(51, 51, 51); font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif; font-size: 14px; line-height: 30px; padding-top: 23px;"><p style="box-sizing: border-box; margin-top: 0px; margin-bottom: 10px;">Assume that the total area is never beyond the maximum possible value of <span style="box-sizing: border-box; font-weight: 700;">int</span>.</p></div><p style="box-sizing: border-box; margin-top: 0px; margin-bottom: 10px; color: rgb(51, 51, 51); font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif; font-size: 14px; line-height: 30px;"><span style="box-sizing: border-box; font-weight: 700;">Credits:</span><br style="box-sizing: border-box;" />Special thanks to <a target=_blank href="https://leetcode.com/discuss/user/mithmatt" style="box-sizing: border-box; color: rgb(0, 136, 204); text-decoration: none; background-position: 0px 0px; background-repeat: initial initial;">@mithmatt</a> for adding this problem, creating the above image and all test cases.</p>
题目很简单,清楚左下角和右上角,求的是两个矩形覆盖的面积,减去重叠部分即可。
int computeArea(int A, int B, int C, int D, int E, int F, int G, int H) {
inline int max(int a,int b) {return a>=b?a:b;}
inline int min(int a,int b) {return a<=b?a:b;}
int I,J,K,L; //四个角
int S1=(C-A)*(D-B);
int S2=(G-E)*(H-F);
I=max(A,E);
J=max(B,F);
K=min(C,G);
L=min(D,H);
if(I>=K||J>=L)
return S1+S2;
else
return S1+S2-(K-I)*(L-J);
}