Easy
給定平面內(nèi)n個(gè)點(diǎn),"boomerang"是一個(gè)數(shù)組(i, j, k)
滿(mǎn)足i
到j
的距離和i
到k
的距離相同(順序需考慮)
找到"boomerang"的個(gè)數(shù)。假設(shè)n<=500, 坐標(biāo)點(diǎn)范圍[-10000, 10000]
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]]
首先建立計(jì)算點(diǎn)到點(diǎn)距離,存儲(chǔ)在矩陣中。距離矩陣每一行有相同數(shù)字,則說(shuō)明對(duì)應(yīng)點(diǎn)距離相同,可以構(gòu)建"boomerang",如果相同數(shù)字有k個(gè),則有k(k-1)中"boomerang"。每一行可能有多個(gè)相同數(shù)字。因?yàn)轫樞蛴绊懡Y(jié)果,所以每行的總"boomerang"數(shù)目加起來(lái)就是總的"boomerang"數(shù)目。我的方法不是很efficient。剛開(kāi)始使用numpy arrary來(lái)存儲(chǔ)dist_matrix出現(xiàn)了超時(shí),改成list后勉強(qiáng)能過(guò),應(yīng)該可以在計(jì)算距離上提高效率(現(xiàn)在重復(fù)計(jì)算了)
from collections import Counter
class Solution(object):
def numberOfBoomerangs(self, points):
"""
:type points: List[List[int]]
:rtype: int
"""
if len(points) < 3:
return 0
else:
total = 0
dist_matrix = [[(i[0]-j[0])**2 + (i[1]-j[1])**2 for j in points] for i in points]
for i in range(len(points)):
for count in Counter(dist_matrix[i]).values():
total += count*(count-1)
return total