题目
题目大意是给定两个长方形的坐标,计算他们一起覆盖的面积。
总的思路很简单,Area_A + Area_B – Overlap,具体求重合的面积则需要计算重合区域的两个坐标点。
那么就要分情况讨论,以重合区左下角点的横坐标为例,需要判断点E与横坐标AC的位置关系,即三种:E<A; A<E<C; C<E。
代码
class Solution { public: int computeArea(int A, int B, int C, int D, int E, int F, int G, int H) { int pt_M[2], pt_N[2]; int area_A_or_B = (C-A)*(D-B) + (G-E)*(H-F); //pt_M[0] if(E<A) pt_M[0] = A; else if(E<=C) pt_M[0] = E; else return area_A_or_B; //pt_N[0] if(G<=A) return area_A_or_B; else if(G<=C) pt_N[0] = G; else pt_N[0] = C; //pt_M[1] if(F<B) pt_M[1] = B; else if(F <= D) pt_M[1] = F; else return area_A_or_B; //pt_N[1] if(H<=B) return area_A_or_B; else if(H<=D) pt_N[1] = H; else pt_N[1] = D; return area_A_or_B - (pt_N[0]-pt_M[0]) * (pt_N[1]-pt_M[1]); } };