假设我们在平面上有n个点,它们成对地分开。现在,“回旋镖”是点(i,j,k)之类的元组,因此i和j之间的距离与i和k之间的距离相同。我们必须找到飞旋镖的数量。
因此,如果输入像[[0,0],[1,0],[2,0]],则输出将为2,因为两个回旋镖分别为[[1,0],[0,0] ,[[2,0]]和[[1,0],[2,0],[0,0]]。
为了解决这个问题,我们将遵循以下步骤-
counter_of_boomerangs:= 0
对于点数组中的每个point_1,执行
n:= distance_count_dict [d]
counter_of_boomerangs:= counter_of_boomerangs + n *(n-1)
x2,y2 = point_2
diff_x:= x2-x1
diff_y:= y2-y1
dist:= diff_x ^ 2 + diff_y ^ 2
distance_count_dict [dist]:= distance_count_dict [dist] + 1
x1,y1 = point_1
定义一个名为distance_count_dict的映射
对于点数组中的每个point_2,执行
对于distance_count_dict中的每个d-
返回counter_of_boomerangs
让我们看下面的实现以更好地理解-
from collections import defaultdict class Solution: def numberOfBoomerangs(self, points): counter_of_boomerangs = 0 for point_1 in points: x1, y1 = point_1 distance_count_dict = defaultdict( int ) for point_2 in points: x2, y2 = point_2 diff_x = x2-x1 diff_y = y2-y1 dist = diff_x ** 2 + diff_y ** 2 distance_count_dict[ dist ] += 1 for d in distance_count_dict: n = distance_count_dict[d] counter_of_boomerangs += n * (n-1) return counter_of_boomerangs ob = Solution()print(ob.numberOfBoomerangs([[0,0],[1,0],[2,0]]))
[[0,0],[1,0],[2,0]]
输出结果
0