几何

                地址: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;

    }
};

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值