Rectangle Area

题目来源
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.

Rectangle Area
Rectangle Area

Assume that the total area is never beyond the maximum possible value of int.
求两个矩形覆盖的面积。
假如没有重叠,直接算俩矩形面积。
假如有重叠,只要两个矩形面积扣除重合部分的面积就可以了。
难点在于如何判断有没有重叠。
重叠的情况实在有点多,我考虑了半天还是没考虑好各种情况。
然后看了下情况,有点巧妙…根本想不到…
说不太清楚,直接看代码吧。

class Solution {
public:
    int computeArea(int A, int B, int C, int D, int E, int F, int G, int H) {
        int left = max(A, E), right = max(min(C, G), left);
        int bottom = max(B, F), top = max(min(D, H), bottom);
        int s1 = (C-A) * (D-B) + (G-E) * (H-F);
        int s2 = (right - left) * (top - bottom);
        return s1 - s2;
    }
};
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容