題目:
給定平面上 n 對不同的點,“迴旋鏢” 是由點表示的元組 (i, j, k)
,其中 i
和 j
之間的距離和 i
和 k
之間的距離相等(需要考慮元組的順序)。
找到所有迴旋鏢的數量。你可以假設 n 最大爲 500,所有點的座標在閉區間[-10000, 10000] 中。
示例:
輸入: [[0,0],[1,0],[2,0]] 輸出: 2 解釋: 兩個迴旋鏢爲 [[1,0],[0,0],[2,0]] 和 [[1,0],[2,0],[0,0]]
python代碼1:
class Solution:
def numberOfBoomerangs(self, points):
res = 0
for x1,y1 in points:
map_dict = {}
for x2,y2 in points:
if (x1-x2)**2 + (y1-y2)**2 in map_dict:
map_dict[(x1-x2)**2 + (y1-y2)**2] += 1
else:
map_dict[(x1-x2)**2 + (y1-y2)**2] = 1
for d in map_dict.values():
res += d*(d-1)
return res
python代碼2:(代碼1升級版)
class Solution(object):
def numberOfBoomerangs(self, points):
res = 0
for x1,y1 in points:
Dict = collections.defaultdict(int)
for x2,y2 in points:
Dict[(x1-x2)**2 + (y1-y2)**2] += 1
for d in Dict.values():
res += d * (d-1)
return res
心得:能用python的內置函數最好要用,實際情況下內置函數更省時間,代碼2的用時是代碼1的1/3.