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:
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]]
方法一:
class Solution {
public:
int numberOfBoomerangs(vector<pair<int, int>>& points) {
int count=0;
for(auto i:points)
{
unordered_map<long,int> distance;
for(auto j:points)
if(i!=j)
distance[pow(i.first-j.first,2)+pow(i.second-j.second,2)]++;
for(auto k:distance)
if(k.second>1)
count +=k.second*(k.second-1);//排列组合
}
return count;
}
};
方法二:摘自讨论区
class Solution{
public:
int numberOfBoomerangs(vector<pair<int, int>>& points) {
int booms = 0;
for (auto &p : points) {
unordered_map<double, int> ctr(points.size());
for (auto &q : points)
booms += 2 * ctr[hypot(p.first - q.first, p.second - q.second)]++;//每增加一个可以凑成同样距离的 “boomerang” 点之后,我们其实就要增加 2 * 当前同距离点的个数 个 “boomerang” 元组可能(也就是该点到同距离的各个点之后,再换个位置,所以 * 2)
}
return booms;
}
};