这道题目的思路比较直接,根据以前做数学题的经验,首先计算出两个长方形的面积,然后进行是否重叠的判断,题目里的重点就在于重叠的判断,判断的方式如下,也比较容易理解:
int left = Math.max(A, E);
int right = Math.min(C, G);
int bottom = Math.max(B, F);
int top = Math.min(D, H);
// Check if overlaps
int overlap = 0;
if(right > left && top > bottom){
overlap = (right - left) * (top - bottom);
}
最后再进行面积的计算即可,面积 = 两个长方形的面积 - 重叠的面积,整体的代码如下:
public class Solution {
public int computeArea(int A, int B, int C, int D, int E, int F, int G, int H) {
// Calculate area of both squares
int areaOfSqrA = (C - A) * (D - B);
int areaOfSqrB = (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);
// Check if overlaps
int overlap = 0;
if(right > left && top > bottom){
overlap = (right - left) * (top - bottom);
}
return areaOfSqrA + areaOfSqrB - overlap;
}
}
知识点:
1. 注意这道题目中重叠的判断方法,不是使用一个很复杂的if语句去判断,这样更加清晰易理解