原题
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]]
解法
遍历points, 对每一个点, 构建一个字典, 字典的键是它与其它点的距离, 值是距离的计数, 计算完距离之后, 我们遍历字典, 求出这个点对应的所有的回旋镖的个数, 用排列组合计算.
Time: O(n**2)
Space: O(n)
代码
class Solution:
def numberOfBoomerangs(self, points: 'List[List[int]]') -> 'int':
res = 0
for x in points:
count = {}
for y in points:
d = (x[0]-y[0])**2 + (x[1]-y[1])**2
count[d] = count.get(d, 0) + 1
# calculate all the boomerang
for d in count:
res += count[d]*(count[d]-1)
return res