博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
[LeetCode] Rectangle Area
阅读量:7250 次
发布时间:2019-06-29

本文共 1852 字,大约阅读时间需要 6 分钟。

Well, this problem looks easy at first glance. However, to get a bug-free code may be not that easy.

The total square is simply equal to the sum of the area of the two rectangles minus the area of their overlap. How do we compute the area of a rectangle? Well, simply times its height with its width. And the height and width can be obtained from the coordinates of the corners.

The key to this problem actually lies in how to handle overlap.

First, let's think about when overlap will happen? Well, if one rectangle is completely to the left (or right/top/bottom) of the other, then no overlap will happen; otherwise, it will.

How do we know whether a rectangle is completely to the left of the other? Well, just make sure that the right boundary of it is to the left of the left boundary of the other. That is, C <= E. The right/top/bottom cases can be handled similarly by A >= GD <= FB >= G.

Now we know how to check for overlap. If overlap happens, how do we compute it? The key is to find the boundary of the overlap.

Take the image at the problem statement as an example. It can be seen that the left boundary of the overlap is max(A, E), the right boundary is min(C, G). The top and bottom boundaries aremin(D, H) and max(B, F) similarly. So the area of the overlap is simply (min(C, G) - max(A, E)) * (min(D, H) - max(B, F)).

You should now convince yourself that all kind of overlapping cases can be handled by the above formula by drawing some examples on the paper.

Finally, we have the following code (simply a translation of the above idea).

1 int computeArea(int A, int B, int C, int D, int E, int F, int G, int H) {2     int s1 = (C - A) * (D - B); 3     int s2 = (G - E) * (H - F);4     if (A >= G || C <= E || D <= F || B >= G)5         return s1 + s2;  6     return s1 + s2 - (min(C, G) - max(A, E)) * (min(D, H) - max(B, F));7 }

转载地址:http://dnebm.baihongyu.com/

你可能感兴趣的文章
微服务指南走北(四):你不愿意做微服务架构的十个理由
查看>>
CSS代码重构与优化之路
查看>>
使用 sigprocmask 和 sigpending 在程序正文中捕获和处理信号
查看>>
Bodymovin插件的使用
查看>>
详细深入分析 Java ClassLoader 工作机制
查看>>
关于设计模式
查看>>
对一个“老”架构的重新思考
查看>>
DoubanFMPlayer, A mimic of Douban.fm player
查看>>
埃森哲、亚马逊和万事达卡抱团推出的区块链项目有何神通?
查看>>
2019年自动驾驶5大趋势预测:第一台Level 5 无人车问世
查看>>
后APP时代的破局之路 :阿里技术“三大容器五大方案”亮相,百川开放全面升级...
查看>>
工欲善其事-必先利其器之终端
查看>>
64位的Mac OS X也有Windows.Forms了
查看>>
立下“去O”Flag的AWS,悄悄修炼了哪些内功?
查看>>
Better Software East/DevOps East/Agile Dev East 2016大会上的教程介绍
查看>>
优酷在多模态内容理解上的研究及应用
查看>>
JavaScript学习笔记整理:对象篇
查看>>
GitHub的bug赏金计划升级:奖金提高到3万美元以上
查看>>
中国法院裁定:禁售部分型号苹果手机
查看>>
使用实体框架、Dapper和Chain的仓储模式实现策略
查看>>