题目
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:
2Explanation:
The two boomerangs are [[1,0],[0,0],[2,0]] and [[1,0],[2,0],[0,0]]
题意
在一个平面中有n个点,“boomerang”就是平面内三元组(i,j,k),也就是三个点,从i到j的距离等于i到k距离。
注意
数据规模为500,算法复杂度选择应该是O(n^2)的
符合条件的三元组顺序(i,j,k)和(i,k,j)
通过距离公式求距离,会涉及到开根号为浮点数,查找表又是精确查找,所以在求距离的时候不开根号
求平方和的过程中可能会造成int类型溢出。该题规定了取值范围两点之间的最大距离就是20000^2+20000^2,并没有溢出
思路
这个的重点在选择什么作为键,什么作为值
通过分析我们知道,i是一个“枢纽“,对于每个i,遍历其余点到i的距离
也就是以距离为键,该距离出现的频次为值,表示到i点等于该距离的点有多少
代码
class Solution {
public:
int numberOfBoomerangs(vector<pair<int, int>>& points) {
int res = 0;
for (int i = 0; i < points.size();i++)
{
//对点i,统计其余点到i的距离
unordered_map<int, int> dismap;
int distance;
for (int j = 0; j < points.size();j++)
{
if (i!=j)
{
int y = points[i].second - points[j].second;
int x = points[i].first - points[j].first;
int dis = y*y + x*x;
dismap[dis]++;
}
}
//对于距离频次大于2,(j,k)选择的可能
for (auto iter = dismap.begin(); iter != dismap.end();iter++)
{
if (iter->second>=2)
{
res += (iter->second * (iter->second - 1));
}
}
}
return res;
}
};