Rectangle Area
来源:互联网 发布:知乎电子书是什么意思 编辑:程序博客网 时间:2024/05/22 00:50
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.
Credits:
Special thanks to @mithmatt for adding this problem, creating the above image and all test cases.
思路:
分为两种情况,
1)两个矩形不相交,则面积直接相加即可;
2)矩形相交,需要面积直接相加,然后减去相交的阴影部分面积。
那么,问题是:如何判断两个矩形相交?
假设两个矩形,分为是A,B,它们的长宽分别是L(A)、W(A)、L(B)、W(B);
A、B的宽度在Y轴投影距离为Y(情况a:如果A、B的宽度在Y轴投影不相交,在Y>=W(A)+W(B)),
A、B的长度在X轴投影距离为X(情况b:如果A、B的宽度在Y轴投影不相交,在X>=L(A)+L(B)),
如果a,b有一种情况发生,则A、B不相交。
见下图。
代码如下:
public class Solution { public int computeArea(int A, int B, int C, int D, int E, int F, int G, int H) { int area1=(D-B)*(C-A); int area2=(H-F)*(G-E); int totalWith=(C-A)+(G-E); int totalHeight=(D-B)+(H-F); int[] w=findMaxAndMin(new int[]{A,E,C,G}); int maxWidthDis=w[0]-w[1];//在X轴上投影,获得实际宽度 int[] h=findMaxAndMin(new int[]{F,B,H,D}); int maxHeightDis=h[0]-h[1];//在Y轴上投影,获得实际高度 if(maxWidthDis>totalWith||maxHeightDis>totalHeight){//不相交 return area1+area2; } return area1+area2-(totalWith-maxWidthDis)*(totalHeight-maxHeightDis);//减去阴影面积 } //b[0]保存最大值,b[1]保存最小值 private int[] findMaxAndMin(int[] a){ int[] b = new int[2]; b[0]=b[1]=a[0]; for(int i=1;i<a.length;i++){ if(a[i]>b[0]){ b[0]=a[i]; }else if(a[i]<b[1]){ b[1]=a[i]; } } return b; }}
0 0
- Rectangle Area
- Rectangle Area
- Rectangle Area
- Rectangle Area
- Rectangle Area
- Rectangle Area
- Rectangle Area
- Rectangle Area
- Rectangle Area
- Rectangle Area
- Rectangle Area
- Rectangle Area
- Rectangle Area
- Rectangle Area
- Rectangle Area
- Rectangle Area
- Rectangle Area
- Rectangle Area
- n个布尔变量,打印所有可能的真值组合
- JAVA在linux上运行带包的class文件
- 数据表设计一些问题_I
- 第二十三篇 Java如何编译 计算器 的源代码共享
- 看懂信息检索和网络数据挖掘领域论文的必备知识总结
- Rectangle Area
- 游戏策划概述(二)——设计
- Android-ToggleButton&CheckTextView&CheckBox
- 对称子字符串的最大长度
- [024] 欢迎大家关注我的微信公众帐号小q机器人(xiaoqrobot)
- 关于dll,lib,h文件
- 分享一个前端等比压缩图片插件
- Linux命令---mpstat命令详解
- 线程 线程组 jvm出来异常组的方法