[英]Given the co-ordinates of n points in 2-D plane, find the number of triplets that form right triangle
I can obviously do this by brute force, by selecting all the triplets one by one and checking if they form a right triangle. 我可以通过蛮力,通过逐个选择所有三胞胎并检查它们是否形成直角三角形来做到这一点。 But what could be a more optimal way?
但是什么可能是更优化的方式? I couldn't think of any.
我什么都想不到。
edit: Since some of you pointed out another question seemingly similar to this one, I went through the answers and I still couldn't figure out how do I solve this one using those answers. 编辑:既然你们中的一些人指出了另一个看似与此问题类似的问题,我会仔细阅读答案,但我仍然无法弄清楚如何使用这些答案来解决这个问题。
This will work in O(n^2Log(n))
. 这将在
O(n^2Log(n))
。
Algo : Algo :
Create a 2D array Slope
, where Slope[i,j]
is slope vector between coordinate[i]
and coordinate[j]
. 创建2D阵列
Slope
,其中Slope[i,j]
是coordinate[i]
和coordinate[j]
之间的斜率矢量。
Now, for coordinate[i]
to be the joint (see note 2) of the right angled triangle , there should be two slopes in Slope[i,....]
which are orthogonal to each other, ie their dot products are 0. 现在,为了使
coordinate[i]
成为直角三角形的关节 (见注2), Slope[i,....]
应该有两个相互正交的Slope[i,....]
,即它们的点积为0 。
If Slope[i,j] = (a,b)
(in vector form)
, then you have to look for (b,-a)
or (-b,a)
in Slope[i,....]
. 如果
Slope[i,j] = (a,b)
(in vector form)
,那么你必须在Slope[i,....]
寻找(b,-a)
或(-b,a)
。
To make search optimized, keep the array Slope[i,...]
sorted on a
or b
. 要使搜索优化,请将数组
Slope[i,...]
排序在a
或b
。 Sorting will take O(nlogn)
time. 排序将花费
O(nlogn)
时间。
Now, for any Slope[i,j]
, do a binary search to look for (b,-a)
and (-b,a)
in array. 现在,对于任何
Slope[i,j]
,进行二进制搜索以在数组中查找(b,-a)
和(-b,a)
。
Binary Search for all n
slopes will take O(nlogn)
time. 所有
n
斜率的二进制搜索将花费O(nlogn)
时间。
So, total Time Complexity : 所以,总时间复杂度 :
= Calculate slope between all points + Sort the slopes + BinarySearch
= O(n*(n+nlogn+nlogn)) = O(n^2log(n))
Note : 注意 :
Make sure to normalize the Slope Vector, ie : 确保标准化斜率向量,即:
coordinate_a = (p,q) coordinate_b = (r,s) slope_vector(a,b) = (pr,qs)/distance(a,b)
Joint of Right Angled Triangle : Common coordinate between two orthogonal edges. 直角三角形的关节:两个正交边之间的公共坐标。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.