给定平面上 n 对 互不相同 的点 points ,其中 points[i] = [xi, yi] 。回旋镖 是由点 (i, j, k) 表示的元组 ,其中 i 和 j 之间的欧式距离和 i 和 k 之间的欧式距离相等(需要考虑元组的顺序)。

返回平面上所有回旋镖的数量。

示例 1: 输入:points = [[0,0],[1,0],[2,0]] 输出:2 解释:两个回旋镖为 [[1,0],[0,0],[2,0]] 和 [1,0],[2,0],[0,0]

示例 2: 输入:points = [[1,1],[2,2],[3,3]] 输出:2

示例 3: 输入:points = [[1,1]] 输出:0

1
2
3
4
5
6
7
8
9
10
11
12
class Solution:
def numberOfBoomerangs(self, points: List[List[int]]) -> int:
ans = 0
for x1, y1 in points:
distance_count = defaultdict(int)
for x2, y2 in points:
d = (x2 - x1) ** 2 + (y2 - y1) ** 2
distance_count[d] += 1
for count in distance_count.values():
if count > 1:
ans += count * (count - 1)
return ans
defaultdict(),字典

这里的defaultdict(function_factory)构建的是一个类似dictionary的对象,其中keys的值,自行确定赋值,但是values的类型,是function_factory的类实例,而且具有默认值。比如default(int)则创建一个类似dictionary对象,里面任何的values都是int的实例,而且就算是一个不存在的key, d[key] 也有一个默认值,这个默认值是int()的默认值0.