Python 中迴旋鏢的數量


假設我們有一個平面上 n 個點,且兩兩間不同。現在一個「迴旋鏢」是指一個點組 (i, j, k) ,其中 i 和 j 之間的距離與 i 和 k 之間的距離相同。我們必須找出迴旋鏢的數量。

因此,如果輸入類似 [[0,0],[1,0],[2,0]],那麼輸出將會是 2,因為兩個迴旋鏢為 [[1,0],[0,0],[2,0]] 和 [[1,0],[2,0],[0,0]]。

為了解此問題,我們將遵循以下步驟-

  • 迴旋鏢計數器 := 0

  • 對於 points 陣列中的每個點_1,請執行

    • x1, y1 = 點_1

    • 定義一個稱為距離計數字典的地圖

    • 對於 points 陣列中的每個點_2,請執行

      • x2, y2 = 點_2

      • diff_x := x2 - x1

      • diff_y := y2 - y1

      • dist := diff_x^2 + diff_y^2

      • 距離計數字典[ dist ] := 距離計數字典[ dist ] + 1

    • 對於距離計數字典中的每個 d,請執行-

      • n := 距離計數字典[d]

      • 迴旋鏢計數器 := 迴旋鏢計數器 + n * (n - 1)

  • 傳回迴旋鏢計數器

範例 

讓我們查看以下實作,以獲得更深入的了解 −

 範例實作

from collections import defaultdict
class Solution:
   def numberOfBoomerangs(self, points):
      counter_of_boomerangs = 0
      for point_1 in points:
         x1, y1 = point_1
         distance_count_dict = defaultdict( int )
         for point_2 in points:
            x2, y2 = point_2
            diff_x = x2-x1
            diff_y = y2-y1
            dist = diff_x ** 2 + diff_y ** 2
            distance_count_dict[ dist ] += 1
         for d in distance_count_dict:
            n = distance_count_dict[d]
            counter_of_boomerangs += n * (n-1)
      return counter_of_boomerangs

ob = Solution()
print(ob.numberOfBoomerangs([[0,0],[1,0],[2,0]]))

輸入

[[0,0],[1,0],[2,0]]

輸出

0

更新於: 10-06-2020

273 次瀏覽

开始你的 职业生涯

完成该课程获得认证

入门
广告
© . All rights reserved.