题目描述:
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.
Assume that the total area is never beyond the maximum possible value of int.
第一版代码:
思路就是先找是否有重叠区域,然后用两个矩形面积之和减去重叠区域,由于没有使用math库中的函数,导致代码显得臃肿,而且一开始写的时候各种情况没考虑完全,比如一个矩形完全包围另一个矩形的情况是提交之后发现WA之后才改的:
int computeArea(int A, int B, int C, int D, int E, int F, int G, int H) { int overlap_area = 0; if(!(G < A || C < E) && !(H < B || D < F)) { int a = 0, b = 0; if(E < A && C < G) a = C - A; else if(A < E && G < C) a = G - E; else a = G-A > C-E ? C-E : G-A; if(B < F && H < D) b = H - F; else if(F < B && D < H) b = D - B; else b = H-B > D-F ? D-F : H-B; overlap_area = a * b; } int area = (C - A ) * (D - B) - overlap_area + (G - E) * (H - F); return area; }
第二个版本的代码是看他人的博客的:
int computeArea(int A, int B, int C, int D, int E, int F, int G, int H) { int overlap_area = ( 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_area = 0; return (C-A) * (D-B) - overlap_area + (G - E) * (H - F); }
这里使用了math库中的函数,非常好用,代码看上去非常简洁,虽然比起第一版的代码运行效率降低了一半,但是很简洁,一旦理解了就不容易出错,这才是好代码!