声明:
今天是第101道题。给定平面上 n 对不同的点,“回旋镖” 是由点表示的元组 (i, j, k)
,其中 i
和 j
之间的距离和 i
和 k
之间的距离相等(需要考虑元组的顺序),找到所有回旋镖的数量。以下所有代码经过楼主验证都能在LeetCode上执行成功,代码也是借鉴别人的,在文末会附上参考的博客链接,如果侵犯了博主的相关权益,请联系我删除
(手动比心ღ( ´・ᴗ・` ))
正文
题目:给定平面上 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。时间复杂度为O(),对每一点计算它和剩下点的距离并存到字典中,键值为其频数freq,那么该点的回旋镖组合为freq*(freq-1),累加所有点的后返回,代码如下。
执行用时: 988 ms, 在Number of Boomerangs的Python提交中击败了38.64% 的用户
class Solution(object):
def numberOfBoomerangs(self, points):
"""
:type points: List[List[int]]
:rtype: int
"""
res = 0
for point1 in points:
record = {}
for point2 in points:
if point1 != point2:
dis = self.distance(point1,point2)
record[dis] = record.get(dis,0)+1
for val in record.values():
res += val*(val-1)
return res
def distance(self,point1,point2):
"""
caculate the euclidean distance between 2 points
"""
return (point1[0]-point2[0])**2 + (point1[1]-point2[1])**2
解法2。计算公式和解法1有点点不一样,这里是对每个遍历的点,出现过的distance放在字典里,键值为对应出现频数freq,每种distance,累加,再对所有distance的这个和累加,代码如下。
执行用时: 756 ms, 在Number of Boomerangs的Python提交中击败了90.34% 的用户
class Solution(object):
def numberOfBoomerangs(self, points):
"""
:type points: List[List[int]]
:rtype: int
"""
res = 0
for point1 in points:
record = {}
for point2 in points:
if point1 != point2:
dis = self.distance(point1,point2)
if dis not in record:
record[dis] = 1
else:
res += record[dis] # freq(freq-1)/2
record[dis] += 1
return 2*res
结尾
解法1:https://blog.csdn.net/qq_17550379/article/details/80638363
解法2:LeetCode