題目
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]]
難度
Easy
方法
對(duì)于每個(gè)point
,用一個(gè)map
統(tǒng)計(jì)各個(gè)距離d
下對(duì)應(yīng)的其他point
的個(gè)數(shù)n
,即map
的key
為距離d
,value
為距離該point
為d
的其他point
的個(gè)數(shù)n
。然后An
取2
,即n*(n-1)
。最后將各個(gè)point
對(duì)應(yīng)的n*(n-1)
累加即可
python代碼
class Solution(object):
def numberOfBoomerangs(self, points):
"""
:type points: List[List[int]]
:rtype: int
"""
result = 0
for point_i in points:
distance_map = {}
for point_j in points:
distance = (point_i[0] - point_j[0]) * (point_i[0] - point_j[0]) + \
(point_i[1] - point_j[1]) * (point_i[1] - point_j[1])
distance_map[distance] = distance_map.get(distance, 0) + 1
for distance in distance_map:
count = distance_map[distance]
result += count * (count - 1)
return result
assert Solution().numberOfBoomerangs([[0,0], [1,0], [2,0]]) == 2