leetcode之Number of Boomerangs(447)
阿新 • • 發佈:2018-11-10
題目:
給定平面上 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.