447. Number of Boomerangs
题目
解题思路
对列表中每一个点p与其他点p计算距离,加入到一个字典d中。
根据d的结果,来判断形成回旋镖的排列组合数量。
代码
易读性与高效性并存的代码:
class Solution:
def numberOfBoomerangs(self, points: 'List[List[int]]') -> 'int':
i = 1
c = 0
for p1 in points:
d = {}
for p2 in points:
x, y = p1[0]-p2[0], p1[1]-p2[1]
distance = x*x + y*y
if distance in d:
d[distance] += 1
else:
d[distance] = 1
for v in d.values():
c += v*(v-1)
return c
最简化代码:但不易读
class Solution:
def numberOfBoomerangs(self, points):
ans = 0
for x1, y1 in points:
cnts = {}
for x2, y2 in points:
dx = x1 - x2
dy = y1 - y2
d = dx * dx + dy * dy
#将计算的部分 和统计合并
if d in cnts:
ans += cnts[d]
cnts[d] += 1
else:
cnts[d] = 1
return 2 * ans