【leetcode】447. Number of Boomerangs【E】

本文介绍了一种高效算法,用于计算平面上特定条件下形成的回旋镖数量。该算法利用距离计算和哈希表来避免重复计算,有效解决了超时和内存溢出的问题。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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 iand 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]]

Subscribe to see which companies asked this question


有三个问题

第一个,最开始的时候还去计算了开平方,但实际上并没有用,而且竟然还用了numpy,实在是不开窍

第二个,最开始的时候虽然结果对,但是一直超时,或者超内存,看了一眼网上的结果,发现,其实并不需要在外面弄一个打的dic,每个循环一个dic就行了

第三个,每个循环,每个节点与其他节点比较就行了

class Solution(object):

    def numberOfBoomerangs(self, points):
        p = points

        res = 0
        for i in xrange(len(p)):
            dic = {}
            for j in xrange(len(p)):

                dist = (p[j][1] - p[i][1])**2 +  (p[j][0] - p[i][0])**2
                dic[dist] = dic.get(dist,0) +1

            #print dic
            for i in dic.values():
                if i > 1:
                    res += i*(i-1)


        return res





评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值