我们只需要算出两个矩形面积的和再减去重合的面积即可。那么算重合的面积,我们只需要把2D转化成1D算出,x和y轴的重合部分即可。常数时间和空间,代码如下:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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