leetcode [223]Rectangle Area
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.

Example:
Input: A = -3, B = 0, C = 3, D = 4, E = 0, F = -1, G = 9, H = 2
Output: 45
题目大意:
计算坐标轴中的面积大小。
解法:
计算两个长方形的面积,如果有重叠的部分,减去重叠部分的面积。我是分情况考虑的,但最后做出来发现忽略了很多情况,参考了网上的解法,这里计算重叠部分的面积很巧妙。
java:
class Solution {
public int computeArea(int A, int B, int C, int D, int E, int F, int G, int H) {
int area1=(C-A)*(D-B),area2=(G-E)*(H-F);
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);
}
return area1+area2-overlap;
}
}

浙公网安备 33010602011771号