- 题目
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]]
- 翻译:
给定在平面上的所有两两不同的点,一个“boomerang”是一个点(i,j,k)的元组,使得i和j之间的距离等于i和k之间的距离 ( 顺序很重要)。
找到所有boomerang的数量。 您可以假设n最多为 500 ,点的坐标全部在 [ - 10000,10000] 的范围内。
- 题解:
class Solution {
public:
int numberOfBoomerangs(vector<pair<int, int>>& points)
{
int ret = 0;
for ( int i = 0; i < points.size() ; i++ )
{
//对于点[i]的记录map,来记录点i到点集中每个点的位置
map<int,int> record;
//遍历除i之外的所有点,以距离为键值,找到到点i距离相同的点有多少个
//这里特别注意.j是从0开始的,因为对这个问题来说(a,b)(b,a)是两个不同的组合
for ( int j = 0; j < points.size() ; j++ )
{
if ( j != i )
{
//这里采用距离的平方,可以避免浮点数的误差
int distance = dis(points[i], points[j]);
//找到后record记录中的点数要+1
record[distance]++;
}
}
// 计算对每一个点来说的,到两个距离相同点的组合的个数
int temp = 0;
for ( map<int,int>::iterator iter = record.begin() ; iter != record.end() ; iter++ )
{
//这里要注意,对每一个点来说,不是单纯的加上距离相同点的个数。这是个计数原理的问题,结果是Cn2,因为选择两次,第一次从n个中进行选择,第二次 //从n-1个中进行选择。(当前点a,候选点b,候选点c)
temp += (*iter).second * ( (*iter).second - 1 );
}
ret += temp;
}
return ret;
}
int dis(pair<int,int> a,pair<int,int> b)
{
int ret = (a.first - b.first) * (a.first - b.first) +
(a.second - b.second) * (a.second - b.second);
return ret;
}
};