题目描述
给定平面上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]]。
使用字典
针对点集中的点,依次遍历其它点求两者之间的距离存储在字典中。当字典中的某一个键值大于1,则累加次数m*(m-1)
。
def numberOfBoomerangs(self, points):
"""
:type points: List[List[int]]
:rtype: int
"""
count = 0
for pi in points:
distance = dict()
for pj in points:
current = (pi[0]-pj[0])**2 + (pi[1]-pj[1])**2
distance[current] = distance.get(current, 0) + 1
for dv in distance.values():
if dv >= 2:
count += dv * (dv - 1)
return count
(最近更新:2019年05月15日)