这是在leetcode上看到的题目。
2个矩形由各自的左下角和右上角来定义。坐标定义为(A,B)(C,D);(E,F)(G,H)。
顶点坐标全部为int整数。
两个矩形分布可以分为三种情况。分离,包含与相交。
代码如下:
public class ReArea { public static int computeArea(int A, int B, int C, int D, int E, int F, int G, int H) { int result = 0; int area1,area2; if(A >= G || B >= H || E >= C || F >= D){ area1 = calArea(A,B,C,D); area2 = calArea(E,F,G,H); result = area1 + area2; } else if((A <= E)&&(C >= G)&&(B <= F)&&(D >= H)){ area1 = calArea(A,B,C,D); result = area1; } else if((A >= E)&&(C <= G)&&(B >= F)&&(D <= H)){ area2 = calArea(E,F,G,H); result = area2; } else{ int[] xLen = {A,C,E,G}; int[] yLen = {B,D,F,H}; sort(xLen); sort(yLen); area1 = calArea(A,B,C,D); area2 = calArea(E,F,G,H); result = area1 + area2 - ((xLen[1] - xLen[2]) * (yLen[1] - yLen[2])); } return result; } public static void sort(int[] dot){ for (int i = 0; i < dot.length; i++) { for (int j = i; j < dot.length; j++) { if (dot[i] < dot[j]) { int temp = dot[i]; dot[i] = dot[j]; dot[j] = temp; } } } } public static int calArea(int x1,int y1,int x2,int y2){ int r1,r2; if (x1 >= x2){ r1 = x1 - x2; }else{ r1 = x2 - x1; } if (y1 >= y2){ r2 = y1 - y2; }else{ r2 = y2 - y1; } return r1 * r2; } public static void main(String args[]){ System.out.print(computeArea(0,0,4,4,0,2,3,3));//output:16 } }