leetcode:447. Number of Boomerangs

来源:互联网 发布:it类书籍 编辑:程序博客网 时间:2024/05/16 14:17

原题的输入输出:

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

直译是找回旋镖的个数。
我将其理解为 :先确定点 i,找到点k,j使得点i、k距离与点ij的距离相等。

class Solution(object):    def numberOfBoomerangs(self, points):        """        :type points: List[List[int]]        :rtype: int        """        ans=0        dic=lambda a,b:(a[0]-b[0])**2+(a[1]-b[1])**2        for i in points:            for k in points:                for j in points:                    if k!=j and k!=i and j!=i:                        if dic(i,k)==dic(i,j):                           ans+=1        return ans

这个代码的问题是,提交会超时,显然三个for循环,这个是o(n*3)的算法。
奇怪的是,当输入[[0,-1],[1,1],[2,0]]时,我认为的输出应该是2,但leetcode的输出却是零。

Tag里面显示用 哈希表来做,所以考虑用字典的方法重做,复杂度是O(n**2)级别的:

class Solution(object):    def numberOfBoomerangs(self, points):        """        :type points: List[List[int]]        :rtype: int        """        ans=0        dic=lambda a,b:(a[0]-b[0])**2+(a[1]-b[1])**2        for i in points:            d={}            for j in points:                if j is not i:                    dist=dic(i,j)                    d[dist]=d.get(dist,0)+1            for k in d:                num=d[k]                if num>=2:                    ans+=num*(num-1)        return ans
0 0