【leetcode】447. Number of Boomerangs【E】

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





發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章