Number of Boomerangs
Given n points in the plane that are all pairwise distinct, a “boomerang” is a tuple of points (i, j, k)
such that the distance between i
and j
equals the distance between i
and k
(the order of the tuple matters).
Find the number of boomerangs. You may assume that n will be at most 500 and coordinates of points are all in the range [-10000, 10000] (inclusive).
Example:
1 | Input: |
Solution
这题标签是 hash table 很明显最佳解法是利用 hash table,依次判断一个点与其他点的距离,如果存在相同距离并且个数不小于2的点(N),任意选择两个点则可以组成回旋镖,排列组合:A(n,m) = n(n-1)(n-2)…(n-m+1),从N中选择两点:A(N,2) = N(N-1),然后累加
Python
1 | class Solution(object): |
简单思考一下:如果增加一个距离相等的点,多出来的组合个数,应该为 (N+1)((N+1)-1) - N(N-1) = 2N,则代码可以修改为:
1 | class Solution(object): |