223. Rectangle Area

Posted yaoyudadudu

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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.

技术分享图片

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;
    }
};

 

以上是关于223. Rectangle Area的主要内容,如果未能解决你的问题,请参考以下文章

223. Rectangle Area

leetcode 223: Rectangle Area

223. Rectangle Area

223. Rectangle Area

LeetCode 223. 矩形面积(Rectangle Area)

LeetCode223. Rectangle Area 解题小结