给定平面上 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]]
解题思路
我们首先想到的解法,将这个元祖所有的组合列出来,然后判断每个组合是不是满足条件,如果满足条件添加到结果中。
class Solution:
def numberOfBoomerangs(self, points):
"""
:type points: List[List[int]]
:rtype: int
"""
def dis(point1, point2):
return (point1[0] - point2[0])**2 + (point1[1] - point2[1])**2
result = 0
for i, a in enumerate(points):
for j, b in enumerate(points[i + 1:]):
for _, c in enumerate(points[j + 1:]):
if dis(a, b) == dis(a, c):
result += 1
return result
这个暴力解法的时间复杂度是O(n^3)
,我们有没有O(n^2)
这个级别的方法呢?我们注意到我们这里有一个中间变量i
,每次都是和i
比较距离。那么我们可以将和i
所有距离的点加到一个record
中,然后通过查找和这个i
的距离相同的点的个数(必须>=2
),计算出这些点对应有多少种组合即可。
class Solution:
def numberOfBoomerangs(self, points):
"""
:type points: List[List[int]]
:rtype: int
"""
def dis(point1, point2):
return (point1[0] - point2[0])**2 + (point1[1] - point2[1])**2
result = 0
for i in points:
record = {}
for j in points:
if j != i:
distance = dis(i, j)
record[distance] = record.get(distance, 0) + 1
for val in record.values():
if val >= 2:
result += (val - 1)* val
return result
我将该问题的其他语言版本添加到了我的GitHub Leetcode
如有问题,希望大家指出!!!