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.

Assume that the total area is never beyond the maximum possible value of int.
Solution 1: simple geometric problem, give code directly.
public class Solution {
public int computeArea(int A, int B, int C, int D, int E, int F, int G, int H) {
int area=Math.abs(D-B)*Math.abs(C-A)+Math.abs(G-E)*Math.abs(H-F);
if (E>=C || A>=G || B>=H || F>=D) return area;
int[] x=new int[]{A,C,E,G};
int[] y=new int[]{D,B,H,F};
Arrays.sort(x);
Arrays.sort(y);
return area-(x[2]-x[1])*(y[2]-y[1]);
}
}
没有评论:
发表评论