Related:
LeetCode 223 - Rectangle Area
LeetCode 850 - Rectangle Area II
LeetCode 939 - Minimum Area Rectangle
LeetCode 963 - Minimum Area Rectangle II
LeetCode – Rectangle Area (Java)
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 coordinates.
http://www.cnblogs.com/easonliu/p/4560596.html
因为只有两个矩形,所以直接算结果 = 两个矩形的面积 - 相交的面积。估计下一道题就会是求多个矩形的覆盖面积了吧。
https://gist.github.com/gcrfelix/bbd71a084a06c23f2384
public int computeArea(int A, int B, int C, int D, int E, int F, int G, int H) {
int left = Math.max(A, E);
int right = Math.min(C, G);
int bottom = Math.max(B, F);
int top = Math.min(D, H);
int overlap = 0;
if(left < right && bottom < top) {
overlap = (right-left)*(top-bottom);
}
int area1 = (C-A)*(D-B);
int area2 = (G-E)*(H-F);
return area1 + area2 - overlap;
}
Read full article from LeetCode – Rectangle Area (Java)
LeetCode 223 - Rectangle Area
LeetCode 850 - Rectangle Area II
LeetCode 939 - Minimum Area Rectangle
LeetCode 963 - Minimum Area Rectangle II
LeetCode – Rectangle Area (Java)
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 coordinates.
http://www.cnblogs.com/easonliu/p/4560596.html
因为只有两个矩形,所以直接算结果 = 两个矩形的面积 - 相交的面积。估计下一道题就会是求多个矩形的覆盖面积了吧。
https://gist.github.com/gcrfelix/bbd71a084a06c23f2384
public int computeArea(int A, int B, int C, int D, int E, int F, int G, int H) { if(C<E||G<A || D<F || H<B) return (G-E)*(H-F) + (C-A)*(D-B); int right = Math.min(C,G); int left = Math.max(A,E); int top = Math.min(H,D); int bottom = Math.max(F,B); return (G-E)*(H-F) + (C-A)*(D-B) - (right-left)*(top-bottom); } |
public int computeArea(int A, int B, int C, int D, int E, int F, int G, int H) {
int left = Math.max(A, E);
int right = Math.min(C, G);
int bottom = Math.max(B, F);
int top = Math.min(D, H);
int overlap = 0;
if(left < right && bottom < top) {
overlap = (right-left)*(top-bottom);
}
int area1 = (C-A)*(D-B);
int area2 = (G-E)*(H-F);
return area1 + area2 - overlap;
}
Read full article from LeetCode – Rectangle Area (Java)