LeetCode 447. 回旋镖的数量

218 阅读1分钟

题目地址(447. 回旋镖的数量)

leetcode-cn.com/problems/nu…

题目描述

给定平面上 n 对 互不相同 的点 points ,其中 points[i] = [xi, yi] 。回旋镖 是由点 (i, j, k) 表示的元组 ,其中 i 和 j 之间的距离和 i 和 k 之间的欧式距离相等(需要考虑元组的顺序)。

返回平面上所有回旋镖的数量。

 

示例 1:

输入:points = [[0,0],[1,0],[2,0]]
输出:2
解释:两个回旋镖为 [[1,0],[0,0],[2,0]][[1,0],[2,0],[0,0]]


示例 2:

输入:points = [[1,1],[2,2],[3,3]]
输出:2


示例 3:

输入:points = [[1,1]]
输出:0


 

提示:

n == points.length
1 <= n <= 500
points[i].length == 2
-104 <= xi, yi <= 104
所有点都 互不相同

思路

通过字典记录间距相同的数值,然后计算组合

代码

  • 语言支持:Python3

Python3 Code:


class Solution:
    def numberOfBoomerangs(self, points: List[List[int]]) -> int:
        res = 0
        length = len(points)
        from collections import defaultdict
        for i in range(length):
            resDict = defaultdict(int)
            for j in range(length):
                #把每个点与i的距离作为字段存储起来
                leng = (points[i][0]-points[j][0])**2 + (points[i][1]-points[j][1])**2
                resDict[leng] += 1
            count = 0
            #有多少个回力标,等于相同间距的数量k*(k-1)组合数
            for k in resDict.values():
                count += k*(k-1)
            res += count
        return res

复杂度分析

令 n 为数组长度。

  • 时间复杂度:O(n2)O(n^2)
  • 空间复杂度:O(logn)O(logn)