地址:223. 矩形面积 - 力扣(LeetCode) (leetcode-cn.com)
该题的核心为求重叠部分的面积:
核心:将两条水平边投影到x轴,将两条竖直边投影到y轴,计算重叠边长,从而计算重叠部分面积
class Solution {
public:
int computeArea(int ax1, int ay1, int ax2, int ay2, int bx1, int by1, int bx2, int by2) {
int x1 = (ax2 - ax1)*(ay2 - ay1) , x2 = (bx2 - bx1)*(by2 - by1);
int a = max(ax1,bx1) , b = min(ax2,bx2);
int c = max(by1,ay1) , d = min(ay2,by2);
int x = max(b-a , 0)*max(d-c,0); //一定注意两条边长度大于零时重叠部分面积才大于零,否则无重叠部分
return x1+x2-x;
}
};
地址:335. 路径交叉 - 力扣(LeetCode) (leetcode-cn.com)
由题意分析知:只能逆时针转,故有三种情况不相交
class Solution {
public:
bool isSelfCrossing(vector<int>& distance) {
int n = distance.size();
if (n < 4) return false;
int step = 2;
// 第一种情况
if (distance[step] < distance[step-2]){ //先判断内卷,如果出现外卷必定相交
while (step < n){
if (distance[step] >= distance[step-2]) return true;
++step;
}
return false;
}
// 从distance[0]开始从内向外绕圈
while (step < n){
if (distance[step] <= distance[step-2]) break; //第一次停止外卷
++step;
}
// 第二种情况
if (step >= n) return false; // 一直外卷无相交
// 第三种情况
bool flag1 = distance[step]+(step >= 4 ? distance[step-4] : 0) >= distance[step-2];
bool flag2 = (step <=n-2 ? distance[step+1] : 0)+(step >= 3 ? distance[step-3] : 0) >= distance[step-1]; //step <= n-2 是为了保证不是最后一次
if (flag1 && flag2) return true; // 两次绕圈的最外层相交
++step;
while (step < n){
if (distance[step] >= distance[step-2]) return true;
++step;
}
return false;
}
};