leetcode_447 回旋镖的数量

124 阅读1分钟

要求

给定平面上 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
  • 所有点都 互不相同

核心代码

class Solution:
    def numberOfBoomerangs(self, points: List[List[int]]) -> int:
        result = 0
        for m in points:
            dic = {}
            for j in points:
                distance = (m[0] - j[0]) ** 2 + (m[1] - j[1]) ** 2
                if distance not in dic:
                    dic[distance] = 1
                else:
                    dic[distance] += 1
            for val in dic.values():
                if val >= 2:
                    result += val * (val - 1)
        return result

image.png

解题思路:这个题其实就是循环遍历然后,将相等的值归结到一起,最核心的部分在与result += val * (val - 1)的理解,我们已经选定了一个起始点,所以假设有其他3个点到这个点的距离是一样的,那么我们从这三个点中选出来两个点和起始点组成回旋镖,第一个点的取值有3种,第二个点的取值有2种,所以总共的取值是3 * 2 =6种。不断的叠加,最终获得总的回旋镖的数量,排列组合。