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.
思路:
见下图。
代码如下:
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;
}
}
原文地址:http://blog.csdn.net/u010786672/article/details/46417935