Number of Boomerangs
Easy
給定平面內n個點,"boomerang"是一個陣列(i, j, k)
滿足i
到j
的距離和i
到k
的距離相同(順序需考慮)
找到"boomerang"的個數。假設n<=500, 座標點範圍[-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]]
首先建立計算點到點距離,儲存在矩陣中。距離矩陣每一行有相同數字,則說明對應點距離相同,可以構建"boomerang",如果相同數字有k個,則有k(k-1)中"boomerang"。每一行可能有多個相同數字。因為順序影響結果,所以每行的總"boomerang"數目加起來就是總的"boomerang"數目。我的方法不是很efficient。剛開始使用numpy arrary來儲存dist_matrix出現了超時,改成list後勉強能過,應該可以在計算距離上提高效率(現在重複計算了)
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
相關文章
- Leetcode 447 Number of BoomerangsLeetCodeOOM
- LeetCode演算法題-Number of Boomerangs(Java實現)LeetCode演算法OOMJava
- JavaScript Number()JavaScript
- Kata:Hamming number
- JavaScript Number toLocaleString()JavaScript
- JavaScript Number toString()JavaScript
- Number.NaNNaN
- JavaScript Number 物件JavaScript物件
- Leetcode Number of islandsLeetCode
- Perfect Number 完美數
- [LeetCode] Third Maximum NumberLeetCode
- [LeetCode] Find the Duplicate NumberLeetCode
- Leetcode 9 Palindrome NumberLeetCode
- Number.parseInt() 方法
- Number.parseFloat()方法
- Number.isSafeInteger()方法
- Number.isNaN()方法NaN
- Number.isFinite()方法
- Js中的NumberJS
- Number.POSITIVE_INFINITY
- Number.ATIVE_INFINITY
- Big Number hd 1212
- 7.104 ITERATION_NUMBER
- react input[type='number']React
- number(p,s)(轉)
- Last digit of a huge numberASTGit
- 136. Single Number
- Serial number lookup for Panasonic
- D. The Number of Imposters
- 65-Valid Number
- [HNU 10072] Fibonacci Number
- Python Number(數字)Python
- Leetcode 933 Number of Recent CallsLeetCode
- [LeetCode] 9. Palindrome NumberLeetCode
- Codeforces 1017 CThe Phone Number
- Number.EPSILON屬性
- Bad magic number for central directory
- 7.34 BITMAP_BUCKET_NUMBER
- number----char(to_char)