当前位置:首页 » 其他

Rectangle Area ---come from leetcode

2015-06-19 17:16 本站整理 浏览(10)
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 * 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 area = (C-A)*(D-B) + (G-E)*(H-F);
if(A>=G || B>=H || C<=E || D<=F)
{
return area;
}
int top = min(D,H);
int bottom = max(B,F);
int right = min(C,G);
int left = max(A,E);
return area - (top-bottom)*(right-left);
}
public int min(int a, int b)
{
if(a > b)
return b;
else
return a;
}
public int max(int a, int b)
{
if(a > b)
return a;
else
return b;
}
}