[LeetCode]447. Number of Boomerangs

题目

Given n points in the plane that are all pairwise distinct, a "boomerang" is a tuple of points (i, j, k) such that the distance between i and j equals the distance between i and k (the order of the tuple matters).

Find the number of boomerangs. You may assume that n will be at most 500 and coordinates of points are all in the range [-10000, 10000] (inclusive).

Example:

Input:
[[0,0],[1,0],[2,0]]

Output:
2

Explanation:
The two boomerangs are [[1,0],[0,0],[2,0]] and [[1,0],[2,0],[0,0]]

难度

Easy

方法

对于每个point,用一个map统计各个距离d下对应的其他point的个数n,即mapkey为距离dvalue为距离该pointd的其他point的个数n。然后An2,即n*(n-1)。最后将各个point对应的n*(n-1)累加即可

python代码

class Solution(object):
    def numberOfBoomerangs(self, points):
        """
        :type points: List[List[int]]
        :rtype: int
        """
        result = 0
        for point_i in points:
            distance_map = {}
            for point_j in points:
                distance = (point_i[0] - point_j[0]) * (point_i[0] - point_j[0]) + \
                           (point_i[1] - point_j[1]) * (point_i[1] - point_j[1])
                distance_map[distance] = distance_map.get(distance, 0) + 1

            for distance in distance_map:
                count = distance_map[distance]
                result += count * (count - 1)

        return result

assert Solution().numberOfBoomerangs([[0,0], [1,0], [2,0]]) == 2
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • **2014真题Directions:Read the following text. Choose the be...
    又是夜半惊坐起阅读 9,941评论 0 23
  • 这里的夜很静, 尘埃落在地上, 激荡出浑厚的声响, 一个人, 无助的蜷缩在空落落的床上, 心的方向迷失了轨迹, 用...
    灰色朦胧阅读 215评论 0 0
  • 昨天介绍了ArrayAdapter的使用,今天介绍一下更加实用的一点,对它进行重写,满足自己的个性化设计需要. A...
    danielss阅读 812评论 0 0