题目:
给定平面上 n 对不同的点,“回旋镖” 是由点表示的元组 (i, j, k) ,其中 i 和 j 之间的距离和 i 和 k 之间的距离相等(需要考虑元组的顺序)。
找到所有回旋镖的数量。你可以假设 n 最大为 500,所有点的坐标在闭区间[-10000, 10000] 中。
示例:
输入: [[0,0],[1,0],[2,0]] 输出: 2 解释: 两个回旋镖为 [[1,0],[0,0],[2,0]] 和 [[1,0],[2,0],[0,0]]
python代码1:
class Solution:
def numberOfBoomerangs(self, points):
res = 0
for x1,y1 in points:
map_dict = {}
for x2,y2 in points:
if (x1-x2)**2 + (y1-y2)**2 in map_dict:
map_dict[(x1-x2)**2 + (y1-y2)**2] += 1
else:
map_dict[(x1-x2)**2 + (y1-y2)**2] = 1
for d in map_dict.values():
res += d*(d-1)
return res
python代码2:(代码1升级版)
class Solution(object):
def numberOfBoomerangs(self, points):
res = 0
for x1,y1 in points:
Dict = collections.defaultdict(int)
for x2,y2 in points:
Dict[(x1-x2)**2 + (y1-y2)**2] += 1
for d in Dict.values():
res += d * (d-1)
return res
心得:能用python的内置函数最好要用,实际情况下内置函数更省时间,代码2的用时是代码1的1/3.
本文介绍了一种计算平面上特定几何结构——回旋镖数量的方法。通过使用Python编程语言,我们实现了两种算法,一种是基本算法,另一种是利用Python内置函数优化后的算法。示例展示了如何对给定点集进行回旋镖数量的计算。
428

被折叠的 条评论
为什么被折叠?



