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.

Rectangle Area

Example:

Input: A = -3, B = 0, C = 3, D = 4, E = 0, F = -1, G = 9, H = 2
Output: 45

Note:

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

 

解题思路:

两个矩形可能重合,所以为两个矩形面积减去重合面积即可。

注意判断是否存在重合时,四个值都要进行比较。

重合矩形的左下角的x值为max(A,E) ,y为max(B,F)

右上角的x值为min(C,G) y 为 min(D,H)

 

代码:

class Solution {
public:
    int computeArea(int A, int B, int C, int D, int E, int F, int G, int H) {
        int area1 = (D-B)*(C-A);
        int area2 = (H-F)*(G-E);
        int ret = area1+area2;
        if(E >= C || F >= D || G <= A || H <= B)
            return ret;
        int I=max(A,E);
        int J=min(C,G);
        int K=max(B,F);
        int L=min(D,H);
        
        ret -= (J-I)*(L-K);
        
        return ret;
    }
};

 

posted @ 2018-06-25 05:21  妖域大都督  阅读(161)  评论(0编辑  收藏  举报