LeetCode OJ 223.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.

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

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 }

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

转载于:https://www.cnblogs.com/liujinhong/p/5374964.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值