生活随笔
收集整理的這篇文章主要介紹了
程序员面试金典 - 面试题 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
;int lx1
,rx1
,by1
,uy1
;int dx1
, dy1
, dx2
, dy2
;
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
總結
以上是生活随笔為你收集整理的程序员面试金典 - 面试题 16.03. 交点(数学)的全部內容,希望文章能夠幫你解決所遇到的問題。
如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。