447 Number of Boomerangs
447. Number of Boomerangs
1. Question
Givennpoints in the plane that are all pairwise distinct, a "boomerang" is a tuple of points(i, j, k)
such that the distance betweeni
andj
equals the distance betweeni
andk
(the order of the tuple matters).
Find the number of boomerangs. You may assume thatnwill be at most 500 and coordinates of points are all in the range [-10000, 10000] (inclusive).
Example:
2. Implementation
思路: (1) 对每个point A,我们都找出它和其他点所形成的距离
(2) 将这些距离存入一个hashmap中,key是距离的值,value是和point A构成这个距离值得点的个数
(3) 接下来如果point A对应的是boomerang的i, 那么我们接下来要求(j, k)的总排列. 遍历hashmap,对于每个key对应的value,根据排列公式 n!/ (n - 2)! = n(n - 1), 能形成boomberangs的个数等于 value * (value - 1)
3. Time & Space Complexity
时间复杂度O(n^2), 空间复杂度O(n)
Last updated