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
andj
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 len = points.size();
int ret = 0;
for(int i = 0; i < len; ++i)
{
map<int,int> res;
for(int j = 0; j < len; ++j)
{
int tmp = dis(points[i],points[j]);
res[tmp]++;
}
for(map<int,int>::iterator it = res.begin(); it != res.end(); ++it)
{
if(it -> second >= 2)
ret = ret + it -> second * (it-> second - 1);
}
}
return ret;
}
int dis(pair<int,int> a,pair<int,int> b)
{
int x = pow(a.first - b.first,2);
int y = pow(a.second - b.second,2);
return x + y;
}
};
核心思想:
1.用map记录下同距离的点数超过2的所有,然后对内部这些点进行排列 比如a 跟b c d 的距离都是相等的
那么会有
a,b a.c
a,b a.d
a.c a.d
然后再调换顺序 乘以2即可 其实最终就是等差数列求和乘以2 就是(n+1)*n /2 * 2 也就是n*(n + 1)