首页 > 其他 > 详细

223 Rectangle Area

时间:2015-06-30 16:22:34      阅读:198      评论:0      收藏:0      [点我收藏+]

223 Rectangle Area

链接:https://leetcode.com/problems/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
Assume that the total area is never beyond the maximum possible value of int.

Credits:
Special thanks to @mithmatt for adding this problem, creating the above image and all test cases.

Hide Tags Math

这个问题是求两个矩形覆盖区域的面积,需要注意的是当两个矩形有重合区域的时候,那么需要减去重合的区域。所以问题的关键就是求重合区域的大小。
定义:

    a= max(A, E);
    b= max(B, F);
    c= min(C, G);
    d= min(D, H);

那么可以知道重合区域的左直线x左边是a,右直线的x坐标是c,上面横向的y坐标是d,下面横线的y坐标是b。那么当c<=或者d<=b的时候没有重叠。反之则有重叠,面积计算方式是 (d-b) * (c -a)。

class Solution {
public:
    int computeArea(int A, int B, int C, int D, int E, int F, int G, int H) {
          int result = (D - B) * (C - A) + (H - F) * (G - E);
          int  a,b,c,d;
          a= max(A, E);
          b= max(B, F);
          c= min(C, G);
          d= min(D, H);
         if (d <= b || c<= a) return result;
         return result - (d-b) * (c -a);
    }
};

版权声明:本文为博主原创文章,未经博主允许不得转载。

223 Rectangle Area

原文:http://blog.csdn.net/efergrehbtrj/article/details/46696641

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!