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:

1
2
3
4
5
6
7
8
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^2次的遍历,将各个点之间的距离存到哈希表当中。如果哈希表的距离统计值超过2,就需要进行计算,得出最终的结果。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
class Solution(object):
def numberOfBoomerangs(self, points):
"""
:type points: List[List[int]]
:rtype: int
"""
length = len(points)
res = 0
for i in range(length):
distlist = []
stats = {}
for j in range(length):
if (i != j):
dist = (points[i][0] - points[j][0]) * (points[i][0] - points[j][0]) + (points[i][1] - points[j][1]) * (points[i][1] - points[j][1])
distlist.append(dist)
# Program optimization: Do not use the 'count' function,
# Using Hashtable is much better, since the cost for "count" function is o(n).
for k in distlist:
if k in stats:
stats[k] += 1
else:
stats[k] = 1
# Count the final number of boomerangs
# The number forms an arithmetic sequence.
for m in stats.values():
if (m == 2):
res += m
elif (m > 2):
res += (m * (m-1))
else:
res = res
return res