Sunday, November 19, 2017

[LeetCode]Rectangle Area


我们只需要算出两个矩形面积的和再减去重合的面积即可。那么算重合的面积,我们只需要把2D转化成1D算出,x和y轴的重合部分即可。常数时间和空间,代码如下:


class Solution {
public:
int computeArea(int A, int B, int C, int D, int E, int F, int G, int H) {
return (C - A) * (D - B) + (G - E) * (H - F) - overlap(A, C, E, G) * overlap(B, D, F, H);
}
private:
int overlap(int A, int B, int C, int D)
{
if(B <= C || A >= D)return 0;
return min(B, D) - max(A, C);
}
};

No comments:

Post a Comment