首页 > 其他 > 详细

LeetCode OJ 223.Rectangle Area

时间:2016-04-10 19:23:26      阅读:184      评论: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.

对于这个问题,如果思路正确,解决起来还是比较简单的。

1.如果没有重叠,则直接返回两个矩形的总面积:(C-A)*(D-B) + (G-E)*(H-F)。判断两个矩形是否重叠:if(C<E || G<A || H<B || D<F)。

2.如果有重叠,计算重叠面积的大小。总面积-重叠面积。

 1 public class Solution {
 2     public int computeArea(int A, int B, int C, int D, int E, int F, int G, int H) {
 3         int total = (C-A)*(D-B) + (G-E)*(H-F);
 4         if(B>H || C<E || D<F || A>G) return total;
 5         int l = 0;
 6         if(E>A) l = Math.min((C-E),(G-E));
 7         else l = Math.min((C-A),(G-A));
 8         int h = 0;
 9         if(D>H) h = Math.min((H-B),(H-F));
10         else h = Math.min((D-B),(D-F));
11         return (total-(l*h));
12     }
13 }

计算重叠部分的长和宽是一个难点,要明确可能重叠的几种情况,然后用简洁的代码把它表示出来。

LeetCode OJ 223.Rectangle Area

原文:http://www.cnblogs.com/liujinhong/p/5374964.html

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