题目:
Given n points in the plane that are all pairwise distinct, a "boomerang" is a tuple of points (i, j, k)
such that the distance between i
and j
equals the distance between i
and k
(the order of the tuple matters).
Find the number of boomerangs. You may assume that n will be at most 500 and coordinates of points are all in the range [-10000, 10000](inclusive).
Example:
Input: [[0,0],[1,0],[2,0]] Output: 2 Explanation: The two boomerangs are [[1,0],[0,0],[2,0]] and [[1,0],[2,0],[0,0]]
题意:
二维平面上给定n个点,找出一些点对(i,j,k),其中点i到点j与点i到点k的距离相等,返回点对的数量
代码:
class Solution(object):
def numberOfBoomerangs(self, points):
"""
:type points: List[List[int]]
:rtype: int
"""
n = len(points)
if n < 3 :
return 0
else :
res = 0 #记录boomerangs数量
for i in range(n) : #第一层循环,遍历所有点
dis = dict() #用字典记录点i到其他点的距离,key为距离,value为这个距离对应的点的个数
for j in range(n) : #第二层循环,计算点i到点j的距离
if j != i :
temp = (points[i][0]-points[j][0])**2 + (points[i][1]-points[j][1])**2 #计算距离,保持距离为平方和的形式
if temp not in dis :
dis[temp] = 0
dis[temp] += 1 #该距离对应的点的个数加1
for k in dis :
if dis[k] >= 2 :
res += dis[k]*(dis[k]-1) #如果某个距离对应的点数量count大于2,计算这些点构成的点对数量为count*(count-1)
return res
笔记:
假设已知点i对应的距离为dis的点的个数为n,则一共有 2*Cn2 = 2*(n*(n-1)/2) = n*(n-1) 种排列组合,故可能存在的点对需要在原来基础上加 n*(n-1)