LeetCode 223 Rectangle Area(矩形面積)
阿新 • • 發佈:2017-06-18
lee return common 分享 span spa class tracking mod
翻譯
找到在二維平面中兩個相交矩形的總面積。
每一個矩形都定義了其左下角和右上角的坐標。
(矩形例如以下圖)
如果,總占地面積永遠不會超過int的最大值。
原文
分析
這題前天試過,寫了一堆推斷。終究還是無果……
貼幾個別人的解決方式……
int computeArea(int A, int B, int C, int D, int E, int F, int G, int H)
{
int64_t xmin1 = min( A, C );
int64_t xmax1 = max( A, C );
int64_t ymin1 = min ( B, D );
int64_t ymax1 = max( B, D );
int64_t xmin2 = min( E, G );
int64_t xmax2 = max( E, G );
int64_t ymin2 = min( F, H );
int64_t ymax2 = max( F, H );
int64_t xa = min( xmax1, xmax2 ) - max( xmin1, xmin2 );
int64_t ya = min( ymax1, ymax2 ) - max( ymin1, ymin2 );
int64_t z = 0 , ca = max( xa, z ) * max( ya, z );
int64_t a1 = (xmax1 - xmin1) * (ymax1 - ymin1);
int64_t a2 = (xmax2 - xmin2) * (ymax2 - ymin2);
return a1 + a2 - ca;
}
int computeArea(int A, int B, int C, int D, int E, int F, int G, int H) {
int overlap = (min(C,G)-max(A,E))*(min(D,H)-max(B,F));
if ( min(C,G)<=max(A,E) || min(D,H)<=max(B,F) )
overlap = 0;
return (C-A)*(D-B)+(G-E)*(H-F)-overlap;
}
int computeArea(int A, int B, int C, int D, int E, int F, int G, int H) {
int common = (C <= E || A >= G || B >= H || D <= F) ? 0 : (min(C, G) - max(A, E)) * (min(D, H) - max(B, F));
return (C - A) * (D - B) + (G - E) * (H - F) - common;
}
LeetCode 223 Rectangle Area(矩形面積)