其实是个很简单的题,但是没有想到思路,给记录一下:
给定平面上 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]]
链接:https://leetcode-cn.com/problems/number-of-boomerangs
这一题python用暴力是过不了的,暴力是O(n^3)
提供一种介于O(n2)和O(n3)的做法
对于每个回旋镖,计算它到其他每个回旋镖的距离,如果有n个回旋镖和这个回旋镖的距离相同,那么形成的回旋镖的数量就是n*(n-1)
class Solution(object):
def numberOfBoomerangs(self, points):
"""
:type points: List[List[int]]
:rtype: int
"""
n = len(points)
count = 0
for i in range(0,n):
dict = {}
for j in range(0,n):
temp = self.distance(points[i],points[j])
if dict.has_key(temp):
dict[temp] = dict[temp] +1
else:
dict[temp] = 1
for temp in dict.keys():
temp1 = dict[temp];
count += temp1 * (temp1 - 1)
return count
def distance(self,point1,point2):
x = point1[0] - point2[0]
y = point1[1] - point2[1]
return x ** 2 + y ** 2