程序员面试金典 - 面试题 16.03. 交点(数学)

1. 题目

给定两条线段(表示为起点start = {X1, Y1}和终点end = {X2, Y2}),如果它们有交点,请计算其交点,没有交点则返回空值。

要求浮点型误差不超过10^-6。若有多个交点(线段重叠)则返回 X 值最小的点,X 坐标相同则返回 Y 值最小的点。

示例 1:
输入:
line1 = {0, 0}, {1, 0}
line2 = {1, 1}, {0, -1}
输出: {0.5, 0}

示例 2:
输入:
line1 = {0, 0}, {3, 3}
line2 = {1, 1}, {2, 2}
输出: {1, 1}

示例 3:
输入:
line1 = {0, 0}, {1, 1}
line2 = {1, 0}, {2, 1}
输出: {},两条线段没有交点
 
提示:
坐标绝对值不会超过 2^7
输入的坐标均是有效的二维坐标

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/intersection-lcci
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

2. 解题

  • 高中数学,求两条直线的交点,解方程,把公式算出来即可
class Solution {
    int lx2,rx2,by2,uy2;//线段2坐标极限值
    int lx1,rx1,by1,uy1;//线段1坐标极限值
    int dx1, dy1, dx2, dy2;//delta
public:
    vector<double> intersection(vector<int>& start1, vector<int>& end1, vector<int>& start2, vector<int>& end2) {
        lx2 = min(start2[0],end2[0]);
        rx2 = max(start2[0],end2[0]);
        by2 = min(start2[1],end2[1]);
        uy2 = max(start2[1],end2[1]);
        lx1 = min(start1[0],end1[0]);
        rx1 = max(start1[0],end1[0]);
        by1 = min(start1[1],end1[1]);
        uy1 = max(start1[1],end1[1]);

        dx1 = start1[0]-end1[0];
        dy1 = start1[1]-end1[1];
        dx2 = start2[0]-end2[0];
        dy2 = start2[1]-end2[1];
        if(dx1*dy2==dx2*dy1)//平行
        {
            vector<vector<int>> ans;
            if(inline2(start1[0],start1[1],start2[0],start2[1]))
            {
                ans.push_back({start1[0],start1[1]});
            }
            if(inline2(end1[0],end1[1],start2[0],start2[1]))
            {
                ans.push_back({end1[0],end1[1]});
            }
            if(inline1(start2[0],start2[1],start1[0],start1[1]))
            {
                ans.push_back({start2[0],start2[1]});
            }
            if(inline1(end2[0],end2[1],start1[0],start1[1]))
            {
                ans.push_back({end2[0],end2[1]});
            }
            if(ans.size()>1)
                sort(ans.begin(), ans.end());
            if(ans.size())
                return {double(ans[0][0]),double(ans[0][1])};
            return {};
        }
        else
        {
            double x = double(dx1*dx2*(start2[1]-start1[1])+dx2*dy1*start1[0]-dx1*dy2*start2[0])/(dx2*dy1-dx1*dy2);
            double y = double(dy1*dy2*(start2[0]-start1[0])+dx1*dy2*start1[1]-dx2*dy1*start2[1])/(dx1*dy2-dx2*dy1);
            if(inline1(x,y,start1[0],start1[1])&&inline2(x,y,start2[0],start2[1]))
                return {x,y};
            return {};
        }

    }

    bool inline1(double x, double y, int x0, int y0)
    {
        return (lx1<=x && x<=rx1 && by1<=y && y<=uy1 && (abs(dx1*(y-y0)-dy1*(x-x0))<0.000001));
    }
    bool inline2(double x, double y, int x0, int y0)
    {
        return (lx2<=x && x<=rx2 && by2<=y && y<=uy2 && (abs(dx2*(y-y0)-dy2*(x-x0))<0.000001));
    }
};

0 ms 11.6 MB

你可能感兴趣的:(《程序员面试金典》)