Leetcode No.223 Rectangle Area 判断矩形相交
发布日期:2021-05-07 23:35:03 浏览次数:19 分类:原创文章

本文共 990 字,大约阅读时间需要 3 分钟。

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-222-2-222
输出

16

上一篇:算法的重要性
下一篇:《Windows程序设计》读书笔五 绘图基础

发表评论

最新留言

关注你微信了!
[***.104.42.241]2025年04月14日 00时29分12秒