码迷,mamicode.com
首页 > 其他好文 > 详细

leetcode 223-Rectangle Area

时间:2015-08-02 00:49:47      阅读:147      评论: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
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!