首页 > 其他 > 详细

leetcode 223-Rectangle Area

时间:2015-08-02 00:46:57      阅读:304      评论:0      收藏:0      [点我收藏+]

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.

 

思路:需要计算正方形覆盖的面积和,关键在于计算重合区域的面积,采用以下计算方式;

设重合区域的左边为(left, bottom)(right, top)

left = Math.max(A, E);

bottom = Math.max(B, F);

right和top的计算比较复杂,需要考虑两个方形不相交的情况,比如:[(-2,-2)(2,2)],[(3,3)(4,4)],

right = Math.max(Math.min(C, G), left);

top = Math.max(Math.min(D, H), bottom);

代码如下:

public int computeArea(int A, int B, int C, int D, int E, int F, int G, int H) {
        int left = Math.max(A, E);
        int right = Math.max(Math.min(C, G), left);
        int bottom = Math.max(B, F);
        int top = Math.max(Math.min(D, H), bottom);
        
        return (G-E)*(H-F)+(C-A)*(D-B)-(right-left)*(top-bottom);
    }

 

leetcode 223-Rectangle Area

原文:http://www.cnblogs.com/linxiong/p/4694906.html

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