0
点赞
收藏
分享

微信扫一扫

223. Rectangle Area

Yaphets_巍 2022-08-03 阅读 30


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.

223. Rectangle Area_leetcode

Assume that the total area is never beyond the maximum possible value of int.

class Solution {
public int computeArea(int A, int B, int C, int D, int E, int F, int G, int H) {
int area = (D - B) * (C - A) + (G - E) * (H - F); // 总面积

int left = Math.max(A, E);
int down = Math.max(B, F);

int right = Math.min(G, C);
int up = Math.min(D, H);

if (up <= down || right <= left) {
return area;
}

area = area - (right - left) * (up - down);

return area;
}
}

class Solution {
public int computeArea(int A, int B, int C, int D, int E, int F, int G, int H) {
long left = Math.max(A, E);
long right = Math.min(C, G);
long top = Math.min(D, H);
long bottom = Math.max(B, F);

long area = (right - left) * (top - bottom);
// if not overlaping, either of these two will be non-posittive
// if right - left = 0, are will automtically be 0 as well
if(right - left < 0 || top - bottom < 0) area = 0;
return (int)((C-A) * (D-B) + (G-E) * (H-F) - area );
}
}


举报

相关推荐

0 条评论