Leetcode No.223 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.


Assume that the total area is never beyond the maximum possible value of  int .

注:题库和图片转自 www.leetcode.com ,所有权归www.leetcode.com仅供交流学习使用,不得用于商业用途

-----------------------------------------------------------------------------------------------------

解题思路:该题的要点是判断两个矩形是否相交,若相交则减去相交的面积。

假设两个矩形若相交则左下点(X1, Y1)  , 右上点(X2, Y2)

一定有以下关系, X1 一定是A,E中最大的值, Y1是B, F中最大的值

X2一定是C, G中最小的值, Y2一定是D,H中最小的值

如果(X1,Y1)在(X2,Y2)的左下方,则两矩形一定相交。因此有解法如下

class Solution {
public:
    int computeArea(int A, int B, int C, int D, int E, int F, int G, int H) {
        int iArea = (C-A)*(D-B)+(G-E)*(H-F);
        int X1, X2, Y1, Y2;
        X1 = (A>E)? A : E;
        Y1 = (B>F)? B : F;
        X2 = (C<G)? C : G;
        Y2 = (D<H)? D : H;
        if(X1 < X2 && Y1 < Y2)
            iArea -= (X2 - X1)*(Y2 - Y1);
        return iArea;
    }
};
输入

-2
-2
2
2
-2
-2
2
2
输出

16

你可能感兴趣的:(LeetCode,算法)